package com.ots.common.utils.poi;
|
import com.ots.common.exception.BusinessException;
|
import com.ots.common.utils.DateUtils;
|
import com.ots.common.utils.StringUtils;
|
import com.ots.common.utils.reflect.ReflectUtils;
|
import com.ots.common.utils.text.Convert;
|
import com.ots.framework.aspectj.lang.annotation.Excel;
|
import com.ots.framework.aspectj.lang.annotation.Excel.ColumnType;
|
import com.ots.framework.aspectj.lang.annotation.Excel.Type;
|
import com.ots.framework.aspectj.lang.annotation.Excels;
|
import com.ots.framework.config.EssConfig;
|
import com.ots.framework.web.domain.AjaxResult;
|
import com.ots.project.exam.domain.TQuestion;
|
import com.ots.project.exam.dto.DataMap;
|
import com.ots.project.exam.dto.QuestionEditItem;
|
import com.ots.project.exam.dto.QuestionItem;
|
import com.ots.project.exam.dto.QuestionJobImport;
|
import com.ots.project.exam.dto.QuestionPersonalityImport;
|
import com.ots.project.tool.exam.JsonUtil;
|
import com.ots.project.tool.exam.ZipUtil;
|
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
|
import org.apache.poi.ss.usermodel.BorderStyle;
|
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.CellStyle;
|
import org.apache.poi.ss.usermodel.CellType;
|
import org.apache.poi.ss.usermodel.DataValidation;
|
import org.apache.poi.ss.usermodel.DataValidationConstraint;
|
import org.apache.poi.ss.usermodel.DataValidationHelper;
|
import org.apache.poi.ss.usermodel.DateUtil;
|
import org.apache.poi.ss.usermodel.FillPatternType;
|
import org.apache.poi.ss.usermodel.Font;
|
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
import org.apache.poi.ss.usermodel.IndexedColors;
|
import org.apache.poi.ss.usermodel.Row;
|
import org.apache.poi.ss.usermodel.Sheet;
|
import org.apache.poi.ss.usermodel.VerticalAlignment;
|
import org.apache.poi.ss.usermodel.Workbook;
|
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
import org.apache.poi.ss.util.CellRangeAddressList;
|
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
|
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.FileNotFoundException;
|
import java.io.FileOutputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.io.OutputStream;
|
import java.lang.reflect.Field;
|
import java.lang.reflect.Method;
|
import java.math.BigDecimal;
|
import java.text.DecimalFormat;
|
import java.util.ArrayList;
|
import java.util.Arrays;
|
import java.util.Date;
|
import java.util.HashMap;
|
import java.util.HashSet;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.Objects;
|
import java.util.Set;
|
import java.util.UUID;
|
|
public class ExcelUtil<T> {
|
|
public static final int sheetSize = 65536;
|
private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
|
|
public Class<T> clazz;
|
|
private String sheetName;
|
|
private Type type;
|
|
private Workbook wb;
|
|
private Sheet sheet;
|
|
private Map<String, CellStyle> styles;
|
|
private List<T> list;
|
|
private List<Object[]> fields;
|
public ExcelUtil(Class<T> clazz) {
|
this.clazz = clazz;
|
}
|
|
public static String convertByExp(String propertyValue, String converterExp) throws Exception {
|
try {
|
String[] convertSource = converterExp.split(",");
|
for (String item : convertSource) {
|
String[] itemArray = item.split("=");
|
if (itemArray[0].equals(propertyValue)) {
|
return itemArray[1];
|
}
|
}
|
} catch (Exception e) {
|
throw e;
|
}
|
return propertyValue;
|
}
|
|
public static String reverseByExp(String propertyValue, String converterExp) throws Exception {
|
try {
|
String[] convertSource = converterExp.split(",");
|
for (String item : convertSource) {
|
String[] itemArray = item.split("=");
|
if (itemArray[1].equals(propertyValue)) {
|
return itemArray[0];
|
}
|
}
|
} catch (Exception e) {
|
throw e;
|
}
|
return propertyValue;
|
}
|
public void init(List<T> list, String sheetName, Type type) {
|
if (list == null) {
|
list = new ArrayList<T>();
|
}
|
this.list = list;
|
this.sheetName = sheetName;
|
this.type = type;
|
createExcelField();
|
createWorkbook();
|
}
|
|
public List<T> importExcel(InputStream input) throws Exception {
|
return importExcel(StringUtils.EMPTY, input);
|
}
|
|
public List<T> importExcel(String sheetName, InputStream input) throws Exception {
|
this.type = Type.IMPORT;
|
this.wb = WorkbookFactory.create(input);
|
List<T> list = new ArrayList<T>();
|
Sheet sheet = null;
|
if (StringUtils.isNotEmpty(sheetName)) {
|
|
sheet = wb.getSheet(sheetName);
|
} else {
|
|
sheet = wb.getSheetAt(0);
|
}
|
if (sheet == null) {
|
throw new IOException("文件sheet不存在");
|
}
|
int rows = sheet.getPhysicalNumberOfRows();
|
if (rows > 0) {
|
|
Map<String, Integer> cellMap = new HashMap<String, Integer>();
|
|
Row heard = sheet.getRow(0);
|
for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
|
Cell cell = heard.getCell(i);
|
if (StringUtils.isNotNull(cell != null)) {
|
String value = this.getCellValue(heard, i).toString();
|
cellMap.put(value, i);
|
} else {
|
cellMap.put(null, i);
|
}
|
}
|
|
Field[] allFields = clazz.getDeclaredFields();
|
|
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
|
for (int col = 0; col < allFields.length; col++) {
|
Field field = allFields[col];
|
Excel attr = field.getAnnotation(Excel.class);
|
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
|
|
field.setAccessible(true);
|
Integer column = cellMap.get(attr.name());
|
fieldsMap.put(column, field);
|
}
|
}
|
for (int i = 1; i < rows; i++) {
|
|
Row row = sheet.getRow(i);
|
T entity = null;
|
for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
|
Object val = this.getCellValue(row, entry.getKey());
|
|
entity = (entity == null ? clazz.newInstance() : entity);
|
|
Field field = fieldsMap.get(entry.getKey());
|
|
Class<?> fieldType = field.getType();
|
if (String.class == fieldType) {
|
String s = Convert.toStr(val);
|
if (StringUtils.endsWith(s, ".0")) {
|
val = StringUtils.substringBefore(s, ".0");
|
} else {
|
val = Convert.toStr(val);
|
}
|
} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
|
val = Convert.toInt(val);
|
} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
|
val = Convert.toLong(val);
|
} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
|
val = Convert.toDouble(val);
|
} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
|
val = Convert.toFloat(val);
|
} else if (BigDecimal.class == fieldType) {
|
val = Convert.toBigDecimal(val);
|
} else if (Date.class == fieldType) {
|
if (val instanceof String) {
|
val = DateUtils.parseDate(val);
|
} else if (val instanceof Double) {
|
val = DateUtil.getJavaDate((Double) val);
|
}
|
}
|
if (StringUtils.isNotNull(fieldType)) {
|
Excel attr = field.getAnnotation(Excel.class);
|
String propertyName = field.getName();
|
if (StringUtils.isNotEmpty(attr.targetAttr())) {
|
propertyName = field.getName() + "." + attr.targetAttr();
|
} else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
|
val = reverseByExp(String.valueOf(val), attr.readConverterExp());
|
}
|
ReflectUtils.invokeSetter(entity, propertyName, val);
|
}
|
}
|
list.add(entity);
|
}
|
}
|
return list;
|
}
|
|
public AjaxResult exportExcel(List<T> list, String sheetName) {
|
this.init(list, sheetName, Type.EXPORT);
|
return exportExcel();
|
}
|
|
public AjaxResult importTemplateExcel(String sheetName) {
|
this.init(null, sheetName, Type.IMPORT);
|
return exportExcel();
|
}
|
public InputStream importReportInterrelatedExcel(String fileName) {
|
InputStream in = null;
|
try {
|
File file = new File(EssConfig.getReportTemplates() + fileName);
|
log.info("loading file = {}",file.getPath());
|
in = new FileInputStream(file);
|
|
} catch (Exception ex) {
|
ex.printStackTrace();
|
}
|
return in;
|
}
|
|
public AjaxResult importTemplateQuestionExcel(String fileName) {
|
this.init(null, sheetName, Type.IMPORT);
|
String returnMessage = "导出模板转移错误:";
|
InputStream in = null;
|
OutputStream out = null;
|
try {
|
in = ExcelUtil.class.getClassLoader().getResourceAsStream("static/downloadTemplates/" + fileName);
|
|
String profile = EssConfig.getProfile();
|
File fileout = new File(profile + "/download" + fileName);
|
if (!fileout.getParentFile().exists()) {
|
fileout.getParentFile().mkdirs();
|
}
|
out = new FileOutputStream(fileout);
|
byte[] buffer = new byte[1024];
|
int length;
|
while ((length = in.read(buffer)) > 0) {
|
out.write(buffer, 0, length);
|
}
|
return AjaxResult.success(fileName);
|
} catch (Exception ex) {
|
returnMessage = returnMessage + ex.getMessage();
|
log.error("导出模板转移错误:{}", returnMessage, ex);
|
} finally {
|
closeChannel(out);
|
closeChannel(in);
|
}
|
return AjaxResult.error(returnMessage);
|
}
|
private void closeChannel(InputStream inputStream) {
|
try {
|
if (Objects.nonNull(inputStream)) {
|
inputStream.close();
|
}
|
} catch (IOException ioe) {
|
log.error("关闭通道失败:{}", ioe.getMessage(), ioe);
|
}
|
}
|
private void closeChannel(OutputStream outputStream) {
|
try {
|
if (Objects.nonNull(outputStream)) {
|
outputStream.close();
|
}
|
} catch (IOException ioe) {
|
log.error("关闭通道失败:{}", ioe.getMessage(), ioe);
|
}
|
}
|
|
public AjaxResult exportExcel() {
|
OutputStream out = null;
|
try {
|
|
double sheetNo = Math.ceil(list.size() / sheetSize);
|
for (int index = 0; index <= sheetNo; index++) {
|
createSheet(sheetNo, index);
|
|
Row row = sheet.createRow(0);
|
int column = 0;
|
|
for (Object[] os : fields) {
|
Excel excel = (Excel) os[1];
|
this.createCell(excel, row, column++);
|
}
|
if (Type.EXPORT.equals(type)) {
|
fillExcelData(index, row);
|
}
|
}
|
String filename = encodingFilename(sheetName);
|
out = new FileOutputStream(getAbsoluteFile(filename));
|
wb.write(out);
|
return AjaxResult.success(filename);
|
} catch (Exception e) {
|
log.error("导出Excel异常{}", e.getMessage());
|
throw new BusinessException("导出Excel失败,请联系网站管理员!");
|
} finally {
|
if (wb != null) {
|
try {
|
wb.close();
|
} catch (IOException e1) {
|
e1.printStackTrace();
|
}
|
}
|
if (out != null) {
|
try {
|
out.close();
|
} catch (IOException e1) {
|
e1.printStackTrace();
|
}
|
}
|
}
|
}
|
|
public void fillExcelData(int index, Row row) {
|
int startNo = index * sheetSize;
|
int endNo = Math.min(startNo + sheetSize, list.size());
|
for (int i = startNo; i < endNo; i++) {
|
row = sheet.createRow(i + 1 - startNo);
|
|
T vo = (T) list.get(i);
|
int column = 0;
|
for (Object[] os : fields) {
|
Field field = (Field) os[0];
|
Excel excel = (Excel) os[1];
|
|
field.setAccessible(true);
|
this.addCell(excel, row, vo, field, column++);
|
}
|
}
|
}
|
|
private Map<String, CellStyle> createStyles(Workbook wb) {
|
|
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
|
CellStyle style = wb.createCellStyle();
|
style.setAlignment(HorizontalAlignment.CENTER);
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
style.setBorderRight(BorderStyle.THIN);
|
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
style.setBorderLeft(BorderStyle.THIN);
|
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
style.setBorderTop(BorderStyle.THIN);
|
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
style.setBorderBottom(BorderStyle.THIN);
|
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
Font dataFont = wb.createFont();
|
dataFont.setFontName("Arial");
|
dataFont.setFontHeightInPoints((short) 10);
|
style.setFont(dataFont);
|
styles.put("data", style);
|
style = wb.createCellStyle();
|
style.cloneStyleFrom(styles.get("data"));
|
style.setAlignment(HorizontalAlignment.CENTER);
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
Font headerFont = wb.createFont();
|
headerFont.setFontName("Arial");
|
headerFont.setFontHeightInPoints((short) 10);
|
headerFont.setBold(true);
|
headerFont.setColor(IndexedColors.WHITE.getIndex());
|
style.setFont(headerFont);
|
styles.put("header", style);
|
return styles;
|
}
|
|
public Cell createCell(Excel attr, Row row, int column) {
|
|
Cell cell = row.createCell(column);
|
|
cell.setCellValue(attr.name());
|
setDataValidation(attr, row, column);
|
cell.setCellStyle(styles.get("header"));
|
return cell;
|
}
|
|
public void setCellVo(Object value, Excel attr, Cell cell) {
|
if (ColumnType.STRING == attr.cellType()) {
|
cell.setCellType(CellType.NUMERIC);
|
cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
|
} else if (ColumnType.NUMERIC == attr.cellType()) {
|
cell.setCellType(CellType.NUMERIC);
|
cell.setCellValue(Integer.parseInt(value + ""));
|
}
|
}
|
|
public void setDataValidation(Excel attr, Row row, int column) {
|
if (attr.name().indexOf("注:") >= 0) {
|
sheet.setColumnWidth(column, 6000);
|
} else {
|
|
sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
|
row.setHeight((short) (attr.height() * 20));
|
}
|
|
if (StringUtils.isNotEmpty(attr.prompt())) {
|
|
setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
|
}
|
|
if (attr.combo().length > 0) {
|
|
setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
|
}
|
}
|
|
public Cell addCell(Excel attr, Row row, T vo, Field field, int column) {
|
Cell cell = null;
|
try {
|
|
row.setHeight((short) (attr.height() * 20));
|
|
if (attr.isExport()) {
|
|
cell = row.createCell(column);
|
cell.setCellStyle(styles.get("data"));
|
|
Object value = getTargetValue(vo, field, attr);
|
String dateFormat = attr.dateFormat();
|
String readConverterExp = attr.readConverterExp();
|
if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) {
|
cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
|
} else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) {
|
cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp));
|
} else {
|
|
setCellVo(value, attr, cell);
|
}
|
}
|
} catch (Exception e) {
|
log.error("导出Excel失败{}", e);
|
}
|
return cell;
|
}
|
|
public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
|
int firstCol, int endCol) {
|
DataValidationHelper helper = sheet.getDataValidationHelper();
|
DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
|
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
|
DataValidation dataValidation = helper.createValidation(constraint, regions);
|
dataValidation.createPromptBox(promptTitle, promptContent);
|
dataValidation.setShowPromptBox(true);
|
sheet.addValidationData(dataValidation);
|
}
|
|
public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
|
DataValidationHelper helper = sheet.getDataValidationHelper();
|
|
DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
|
|
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
|
|
DataValidation dataValidation = helper.createValidation(constraint, regions);
|
|
if (dataValidation instanceof XSSFDataValidation) {
|
dataValidation.setSuppressDropDownArrow(true);
|
dataValidation.setShowErrorBox(true);
|
} else {
|
dataValidation.setSuppressDropDownArrow(false);
|
}
|
sheet.addValidationData(dataValidation);
|
}
|
|
public String encodingFilename(String filename) {
|
filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
|
return filename;
|
}
|
|
public String getAbsoluteFile(String filename) {
|
String downloadPath = EssConfig.getDownloadPath() + filename;
|
File desc = new File(downloadPath);
|
if (!desc.getParentFile().exists()) {
|
desc.getParentFile().mkdirs();
|
}
|
return downloadPath;
|
}
|
|
public File getAbsoluteFileByName(String filename) {
|
String downloadPath = EssConfig.getDownloadPath() + "/" + filename;
|
File desc = new File(downloadPath);
|
if (!desc.getParentFile().exists()) {
|
desc.getParentFile().mkdirs();
|
}
|
return desc;
|
}
|
public File getAbsoluteFileZipByName(String filename) {
|
String downloadPath = EssConfig.getDownloadPath() + filename;
|
File desc = new File(downloadPath);
|
if (!desc.getParentFile().exists()) {
|
desc.getParentFile().mkdirs();
|
}
|
return desc;
|
}
|
|
private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
|
Object o = field.get(vo);
|
if (StringUtils.isNotEmpty(excel.targetAttr())) {
|
String target = excel.targetAttr();
|
if (target.indexOf(".") > -1) {
|
String[] targets = target.split("[.]");
|
for (String name : targets) {
|
o = getValue(o, name);
|
}
|
} else {
|
o = getValue(o, target);
|
}
|
}
|
return o;
|
}
|
|
private Object getValue(Object o, String name) throws Exception {
|
if (StringUtils.isNotEmpty(name)) {
|
Class<?> clazz = o.getClass();
|
String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
|
Method method = clazz.getMethod(methodName);
|
o = method.invoke(o);
|
}
|
return o;
|
}
|
|
private void createExcelField() {
|
this.fields = new ArrayList<Object[]>();
|
List<Field> tempFields = new ArrayList<>();
|
tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
|
tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
|
for (Field field : tempFields) {
|
|
if (field.isAnnotationPresent(Excel.class)) {
|
putToField(field, field.getAnnotation(Excel.class));
|
}
|
|
if (field.isAnnotationPresent(Excels.class)) {
|
Excels attrs = field.getAnnotation(Excels.class);
|
Excel[] excels = attrs.value();
|
for (Excel excel : excels) {
|
putToField(field, excel);
|
}
|
}
|
}
|
}
|
|
private void putToField(Field field, Excel attr) {
|
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
|
this.fields.add(new Object[]{field, attr});
|
}
|
}
|
|
public void createWorkbook() {
|
this.wb = new SXSSFWorkbook(500);
|
}
|
|
public void createSheet(double sheetNo, int index) {
|
this.sheet = wb.createSheet();
|
this.styles = createStyles(wb);
|
|
if (sheetNo == 0) {
|
wb.setSheetName(index, sheetName);
|
} else {
|
wb.setSheetName(index, sheetName + index);
|
}
|
}
|
|
public Object getCellValue(Row row, int column) {
|
if (row == null) {
|
return row;
|
}
|
Object val = "";
|
try {
|
Cell cell = row.getCell(column);
|
if (cell != null) {
|
if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) {
|
val = cell.getNumericCellValue();
|
if (HSSFDateUtil.isCellDateFormatted(cell)) {
|
val = DateUtil.getJavaDate((Double) val);
|
} else {
|
if ((Double) val % 1 > 0) {
|
val = new DecimalFormat("0.00").format(val);
|
} else {
|
val = new DecimalFormat("0").format(val);
|
}
|
}
|
} else if (cell.getCellTypeEnum() == CellType.STRING) {
|
val = cell.getStringCellValue();
|
} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
|
val = cell.getBooleanCellValue();
|
} else if (cell.getCellTypeEnum() == CellType.ERROR) {
|
val = cell.getErrorCellValue();
|
}
|
}
|
} catch (Exception e) {
|
return val;
|
}
|
return val;
|
}
|
|
public AjaxResult exportExcelByDataMap(DataMap<Integer, Object[]> dataMap, String fileName) {
|
|
XSSFWorkbook workbook = new XSSFWorkbook();
|
|
XSSFSheet sheet = workbook.createSheet(fileName);
|
|
Set<Integer> keySet = new HashSet<>(dataMap.getKeys());
|
int rowNum = 0;
|
for (Integer key : keySet) {
|
Row row = sheet.createRow(rowNum);
|
Object[] objArr = dataMap.getValues().get(key);
|
int cellNum = 0;
|
for (Object obj : objArr) {
|
Cell cell = row.createCell(cellNum);
|
if (obj instanceof String) {
|
cell.setCellValue((String) obj);
|
if (rowNum == 0) {
|
sheet.autoSizeColumn(cellNum);
|
int length = sheet.getColumnWidth(cellNum) * 17 / 10;
|
sheet.setColumnWidth(cellNum, length < 65270 ? length : 65270);
|
}
|
} else if (obj instanceof Integer) {
|
cell.setCellValue((Integer) obj);
|
}
|
cellNum++;
|
}
|
rowNum++;
|
}
|
FileOutputStream out = null;
|
FileOutputStream zipOut = null;
|
this.sheetName = "report";
|
try {
|
String fileSuffix = ".xlsx";
|
String zipSuffix = ".zip";
|
File file = getAbsoluteFileByName(fileName + fileSuffix);
|
File fileZip = getAbsoluteFileZipByName(fileName + zipSuffix);
|
out = new FileOutputStream(file);
|
zipOut = new FileOutputStream(fileZip);
|
workbook.write(out);
|
List<File> fileList = new ArrayList<>();
|
fileList.add(file);
|
ZipUtil.toZip(fileList, zipOut);
|
file.delete();
|
return AjaxResult.success(fileName + zipSuffix);
|
} catch (Exception e) {
|
log.error("导出Excel异常{}", e.getMessage());
|
throw new BusinessException("导出Excel失败,请联系网站管理员!");
|
} finally {
|
if (out != null) {
|
try {
|
out.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
if (zipOut != null) {
|
try {
|
zipOut.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
if (workbook != null) {
|
try {
|
workbook.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
}
|
|
public List<Map<Integer, String>> importDynamicExcel(InputStream is) throws Exception {
|
|
this.type = Type.IMPORT;
|
this.wb = WorkbookFactory.create(is);
|
List<Map<Integer, String>> excelList = new ArrayList<>();
|
Sheet sheet = null;
|
if (StringUtils.isNotEmpty(sheetName)) {
|
|
sheet = wb.getSheet(sheetName);
|
} else {
|
|
sheet = wb.getSheetAt(0);
|
}
|
if (sheet == null) {
|
throw new IOException("文件sheet不存在");
|
}
|
|
int rows = sheet.getPhysicalNumberOfRows();
|
if (rows < 0) {
|
return excelList;
|
}
|
|
Field[] allFields = clazz.getDeclaredFields();
|
Map<Integer, String> attrMap = new HashMap<>();
|
for (int i = 0; i < allFields.length; i++) {
|
Excel attr = allFields[i].getAnnotation(Excel.class);
|
if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
|
attrMap.put(i, attr.name());
|
}
|
}
|
|
Map<Integer, String> cellHeadMap = new HashMap<Integer, String>();
|
Row heard = sheet.getRow(0);
|
for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
|
Cell cell = heard.getCell(i);
|
if (StringUtils.isNotNull(cell != null)) {
|
String value = this.getCellValue(heard, i).toString();
|
cellHeadMap.put(i, value);
|
} else {
|
cellHeadMap.put(i, null);
|
}
|
}
|
|
|
for (int i = 0; i < 3; i++) {
|
if (!cellHeadMap.get(i).contains(attrMap.get(i))) {
|
return excelList;
|
}
|
}
|
|
excelList.add(cellHeadMap);
|
QuestionJobImport questionJobImport = (QuestionJobImport) clazz.newInstance();
|
|
for (int i = 1; i < rows; i++) {
|
|
Row data = sheet.getRow(i);
|
Map<Integer, String> cellDataMap = new HashMap<Integer, String>();
|
for (int j = 0; j < data.getPhysicalNumberOfCells(); j++) {
|
Cell cell = data.getCell(j);
|
if (StringUtils.isNotNull(cell != null)) {
|
String value = this.getCellValue(data, j).toString();
|
cellDataMap.put(j, value);
|
} else {
|
cellDataMap.put(j, null);
|
}
|
}
|
excelList.add(cellDataMap);
|
}
|
return excelList;
|
}
|
|
public QuestionJobImport importJobExcel(InputStream is, Long levelId, String levelName, String langType) throws Exception {
|
|
this.type = Type.IMPORT;
|
this.wb = WorkbookFactory.create(is);
|
QuestionJobImport questionJobImport = (QuestionJobImport) clazz.newInstance();
|
|
questionJobImport.setLangType(langType);
|
|
Sheet questionSheet = wb.getSheetAt(0);
|
if (questionSheet == null) {
|
throw new IOException("文件sheet不存在");
|
}
|
|
int questionRows = questionSheet.getPhysicalNumberOfRows();
|
if (questionRows < 0) {
|
return questionJobImport;
|
}
|
|
Map<Integer, String> cellHeadMap = new HashMap<Integer, String>();
|
Row heard = questionSheet.getRow(0);
|
|
int colNum = heard.getPhysicalNumberOfCells();
|
|
|
List<String> multilingualList = new ArrayList<>();
|
for (int i = 0; i < colNum; i++) {
|
Cell cell = heard.getCell(i);
|
String value = "";
|
if (Objects.nonNull(cell) && StringUtils.isNotEmpty(value = this.getCellValue(heard, i).toString().trim())) {
|
cellHeadMap.put(i, value);
|
multilingualList.add(value);
|
}
|
}
|
|
if (!StringUtils.equals(cellHeadMap.get(0), "ID")) {
|
questionJobImport.setLangType("");
|
return questionJobImport;
|
}
|
|
questionJobImport.setPermanentIdList(new ArrayList<>());
|
List<String> permanentIdList = questionJobImport.getPermanentIdList();
|
|
questionJobImport.setQuestionStrList(new ArrayList<>());
|
List<String> questionStrList = questionJobImport.getQuestionStrList();
|
|
questionJobImport.setItemList(new ArrayList<>());
|
List<QuestionItem> itemsList = questionJobImport.getItemList();
|
|
Set<Integer> colNumSet = new HashSet<>();
|
for (int i = 1; i < questionRows; i++) {
|
Row data = questionSheet.getRow(i);
|
for (int j = 1; j < colNum; j++) {
|
Cell questionCell = data.getCell(j);
|
if (Objects.nonNull(questionCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
|
colNumSet.add(j);
|
}
|
}
|
}
|
|
List<String> multilingualResultList = new ArrayList<>();
|
if (StringUtils.equals(langType, "ALL")) {
|
for (int langNum : colNumSet) {
|
multilingualResultList.add(multilingualList.get(langNum));
|
}
|
} else {
|
for (int langNum : colNumSet) {
|
if (StringUtils.equals(langType, multilingualList.get(langNum))) {
|
multilingualResultList.add(multilingualList.get(langNum));
|
}
|
}
|
}
|
|
if (multilingualResultList.isEmpty()) {
|
questionJobImport.setLangType("");
|
return questionJobImport;
|
}
|
questionJobImport.setMultilingualList(multilingualResultList);
|
questionJobImport.setQuestionList(new ArrayList<>());
|
List<TQuestion> tQuestionList = questionJobImport.getQuestionList();
|
|
for (int i = 1; i < questionRows; i++) {
|
|
Row data = questionSheet.getRow(i);
|
if (this.getCellValue(data, 0).toString().trim().isEmpty()) {
|
break;
|
}
|
|
Cell permanentCell = data.getCell(0);
|
if (StringUtils.isNotNull(permanentCell)) {
|
permanentIdList.add(this.getCellValue(data, 0).toString().trim());
|
}
|
|
Map<String, String> questionMap = new HashMap<>();
|
for (int j : colNumSet) {
|
Cell questionCell = data.getCell(j);
|
if (StringUtils.isNotNull(questionCell)) {
|
questionMap.put(cellHeadMap.get(j), this.getCellValue(data, j).toString().trim());
|
}
|
}
|
questionStrList.add(JsonUtil.toJsonStr(questionMap));
|
|
TQuestion question = new TQuestion();
|
|
question.setPermanentId(permanentIdList.get(i - 1));
|
question.setDeleted(1L);
|
question.setLangType("English");
|
question.setLevelId(levelId);
|
question.setLevelName(levelName);
|
question.setTitle(JsonUtil.toJsonStr(questionMap));
|
tQuestionList.add(question);
|
}
|
return questionJobImport;
|
}
|
|
public QuestionPersonalityImport importPersonalityExcel(InputStream is, Long levelId, String levelName, String langType) throws Exception {
|
|
this.type = Type.IMPORT;
|
this.wb = WorkbookFactory.create(is);
|
QuestionPersonalityImport questionPersonalityImport = (QuestionPersonalityImport) clazz.newInstance();
|
|
questionPersonalityImport.setLangType(langType);
|
|
Sheet questionSheet = wb.getSheetAt(0);
|
|
Sheet itemSheet = wb.getSheetAt(1);
|
|
if (questionSheet == null || itemSheet == null) {
|
throw new IOException("file sheet does not exist");
|
}
|
|
int questionRows = questionSheet.getPhysicalNumberOfRows();
|
int itemRows = itemSheet.getPhysicalNumberOfRows();
|
if (questionRows < 0 || itemRows < 0) {
|
return questionPersonalityImport;
|
}
|
|
Row questionHead = questionSheet.getRow(0);
|
Row itemHead = itemSheet.getRow(0);
|
|
int questionHeadColNum = questionHead.getPhysicalNumberOfCells();
|
int itemHeadColNum = itemHead.getPhysicalNumberOfCells();
|
|
Map<Integer, String> questionHeadMap = new HashMap<>();
|
|
Map<Integer, String> itemHeadMap = new HashMap<>();
|
|
List<String> multilingualList = new ArrayList<>();
|
for (int i = 0; i < questionHeadColNum; i++) {
|
Cell cell = questionHead.getCell(i);
|
String value = "";
|
if (Objects.nonNull(cell) && StringUtils.isNotEmpty(this.getCellValue(questionHead, i).toString().trim())) {
|
value = this.getCellValue(questionHead, i).toString().trim();
|
questionHeadMap.put(i, value);
|
multilingualList.add(value);
|
}
|
}
|
|
if (!StringUtils.equals(questionHeadMap.get(0), "ID")) {
|
questionPersonalityImport.setLangType("");
|
return questionPersonalityImport;
|
}
|
for (int i = 0; i < itemHeadColNum; i++) {
|
Cell cell = itemHead.getCell(i);
|
if (StringUtils.isNotNull(cell != null)) {
|
String value = this.getCellValue(itemHead, i).toString();
|
itemHeadMap.put(i, value);
|
} else {
|
itemHeadMap.put(i, "");
|
}
|
}
|
|
|
questionPersonalityImport.setQuestionList(new ArrayList<>());
|
List<TQuestion> questionList = questionPersonalityImport.getQuestionList();
|
|
|
List<QuestionEditItem> items = new ArrayList<>();
|
|
Set<Integer> qustionNumSet = new HashSet<>();
|
for (int i = 1; i < questionRows; i++) {
|
Row data = questionSheet.getRow(i);
|
for (int j = 1; j < questionHeadColNum; j++) {
|
Cell questionCell = data.getCell(j);
|
if (Objects.nonNull(questionCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
|
qustionNumSet.add(j);
|
}
|
}
|
}
|
Set<Integer> itemNumSet = new HashSet<>();
|
for (int i = 1; i < itemRows; i++) {
|
Row data = itemSheet.getRow(i);
|
for (int j = 1; j < itemHeadColNum; j++) {
|
Cell itemCell = data.getCell(j);
|
if (Objects.nonNull(itemCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
|
itemNumSet.add(j);
|
}
|
}
|
}
|
|
if (qustionNumSet.size() > itemNumSet.size()) {
|
questionPersonalityImport.setLangType("");
|
return questionPersonalityImport;
|
}
|
|
for (int i = 1; i < questionHeadMap.size(); i++) {
|
if (!itemHeadMap.containsValue(questionHeadMap.get(i))) {
|
questionPersonalityImport.setLangType("");
|
return questionPersonalityImport;
|
}
|
}
|
|
List<String> multilingualResultList = new ArrayList<>();
|
if (StringUtils.equals(langType, "ALL")) {
|
for (int langNum : qustionNumSet) {
|
multilingualResultList.add(multilingualList.get(langNum));
|
}
|
} else {
|
for (int langNum : qustionNumSet) {
|
if (StringUtils.equals(langType, multilingualList.get(langNum))) {
|
multilingualResultList.add(multilingualList.get(langNum));
|
}
|
}
|
}
|
|
if (multilingualResultList.isEmpty()) {
|
questionPersonalityImport.setLangType("");
|
return questionPersonalityImport;
|
}
|
questionPersonalityImport.setMultilingualList(multilingualResultList);
|
for (int i = 1; i < itemRows; i++) {
|
|
Row rowDatas = itemSheet.getRow(i);
|
|
if (this.getCellValue(rowDatas, 0).toString().trim().isEmpty()) {
|
throw new IOException("No question options");
|
}
|
|
Cell permanentCell = rowDatas.getCell(0);
|
String prefix = "";
|
if (StringUtils.isNotNull(permanentCell)) {
|
prefix = this.getCellValue(rowDatas, 0).toString().trim();
|
}
|
|
QuestionEditItem questionEditItem = new QuestionEditItem();
|
questionEditItem.setPrefix(prefix);
|
Map<String, String> itemContentMap = new HashMap<>();
|
for (int j = 1; j < itemHeadColNum; j++) {
|
Cell questionCell = rowDatas.getCell(j);
|
if (StringUtils.isNotNull(questionCell)) {
|
itemContentMap.put(itemHeadMap.get(j), this.getCellValue(rowDatas, j).toString().trim());
|
}
|
}
|
questionEditItem.setContent(JsonUtil.toJsonStr(itemContentMap));
|
items.add(questionEditItem);
|
}
|
|
for (int i = 1; i < questionRows; i++) {
|
|
Row rowDatas = questionSheet.getRow(i);
|
|
if (this.getCellValue(rowDatas, 0).toString().trim().isEmpty()) {
|
break;
|
}
|
|
Cell permanentCell = rowDatas.getCell(0);
|
String permanentId = "";
|
if (StringUtils.isNotNull(permanentCell)) {
|
permanentId = this.getCellValue(rowDatas, 0).toString().trim();
|
}
|
|
TQuestion question = new TQuestion();
|
|
question.setPermanentId(permanentId);
|
question.setDeleted(1L);
|
question.setLangType("English");
|
question.setLevelId(levelId);
|
question.setLevelName(levelName);
|
|
question.setChoiceInput(new ArrayList<>());
|
question.setSelectInput(new ArrayList<>());
|
List<String> choiceInput = question.getChoiceInput();
|
List<String> selectInput = question.getSelectInput();
|
|
items.stream().forEach(questionEditItem -> {
|
choiceInput.add(questionEditItem.getPrefix());
|
selectInput.add(questionEditItem.getContent());
|
});
|
Map<String, String> questionTitleMap = new HashMap<>();
|
for (int j : qustionNumSet) {
|
Cell questionCell = rowDatas.getCell(j);
|
if (StringUtils.isNotNull(questionCell)) {
|
|
questionTitleMap.put(questionHeadMap.get(j), this.getCellValue(rowDatas, j).toString().trim());
|
}
|
}
|
question.setTitle(JsonUtil.toJsonStr(questionTitleMap));
|
questionList.add(question);
|
}
|
return questionPersonalityImport;
|
}
|
public Map<String, Map<String, String>> getMAQFromExcel() {
|
InputStream is = null;
|
Map<String, Map<String, String>> mapMap = new HashMap<>();
|
try {
|
|
is = new FileInputStream(new File(EssConfig.getReportTemplates() + "MAQ掌骏数据试用个人.xlsx"));
|
this.type = Type.IMPORT;
|
this.wb = WorkbookFactory.create(is);
|
|
Sheet sheet = wb.getSheetAt(0);
|
Row head = sheet.getRow(0);
|
int colNum = head.getPhysicalNumberOfCells();
|
int rowsNum = sheet.getPhysicalNumberOfRows();
|
|
List<String> headValueList = new ArrayList<>();
|
for (int i = 0; i < colNum; i++) {
|
Cell cell = head.getCell(i);
|
String value = "";
|
if (Objects.nonNull(cell) && StringUtils.isNotEmpty(this.getCellValue(head, i).toString().trim())) {
|
value = this.getCellValue(head, i).toString().trim();
|
headValueList.add(value);
|
|
}
|
}
|
|
for (int i = 1; i < rowsNum; i++) {
|
|
Row data = sheet.getRow(i);
|
Cell questionCellName = data.getCell(0);
|
Map<String, String> valueMap = new HashMap<>();
|
if (Objects.nonNull(questionCellName) && StringUtils.isNotEmpty(this.getCellValue(data, 0).toString().trim())) {
|
mapMap.put(this.getCellValue(data, 0).toString().trim(), valueMap);
|
} else {
|
continue;
|
}
|
for (int j = 1; j < colNum; j++) {
|
Cell questionCell = data.getCell(j);
|
if (Objects.nonNull(questionCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
|
|
String strValue = "";
|
try {
|
strValue = String.valueOf(Math.round(Double.parseDouble(this.getCellValue(data, j).toString().trim())));
|
} catch (Exception e) {
|
strValue = this.getCellValue(data, j).toString().trim();
|
}
|
|
|
valueMap.put(headValueList.get(j), strValue);
|
}
|
}
|
}
|
} catch (FileNotFoundException e) {
|
e.printStackTrace();
|
e.printStackTrace();
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
if (Objects.nonNull(is)) {
|
try {
|
is.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
return mapMap;
|
}
|
}
|