使用easyexcel方式解析数据的工具类(EasyExcel):
package org.jeecg.modules.mes.utils;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import javax.mail.Message;
import java.lang.reflect.Field;
import java.util.*;
@Component
public class EasyExcelUtils extends AnalysisEventListener<Object> {
List<Object> list = new ArrayList<Object>();
Class clazz;
public EasyExcelUtils() {
super();
}
public EasyExcelUtils(Class clazz) {
super();
this.clazz = clazz;
}
@Override
public void invoke(Object data, AnalysisContext context) {
list.add(data);
}
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
Map<Integer, String> head = new HashMap<>();
try {
head = getIndexNameMap(clazz);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
Set<Integer> keySet = head.keySet();
for (Integer key : keySet) {
if (StringUtils.isEmpty(headMap.get(key))) {
throw new ExcelAnalysisException("解析excel出错,请传入正确格式的excel");
}
if (!headMap.get(key).equals(head.get(key))) {
throw new ExcelAnalysisException("解析excel出错,请传入正确格式的excel");
}
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
public Map<Integer, String> getIndexNameMap(Class clazz) throws NoSuchFieldException {
Map<Integer, String> result = new HashMap<>();
Field field;
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
field = clazz.getDeclaredField(fields[i].getName());
field.setAccessible(true);
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty != null) {
int index = excelProperty.index();
String[] values = excelProperty.value();
StringBuilder value = new StringBuilder();
for (String v : values) {
value.append(v);
}
result.put(index, value.toString());
}
}
return result;
}
@Override
public void onException(Exception exception, AnalysisContext context) {
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
}
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public Message getMessage() {
return null;
}
public void setMessage(Message message) {
}
}
导出工具类(ExcelExportUtils):
package org.jeecg.modules.mes.utils;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelExportUtils {
private static final Logger logger = LoggerFactory.getLogger(ExcelExportUtils.class);
private static Sheet initSheet;
static {
initSheet = new Sheet(1, 0);
initSheet.setSheetName("sheet");
initSheet.setAutoWidth(Boolean.TRUE);
}
public static List<Object> readLessThan1000Row(String filePath) {
return readLessThan1000RowBySheet(filePath, null);
}
public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet) {
sheet = sheet != null ? sheet : initSheet;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
return EasyExcelFactory.read(inputStream, sheet);
} catch (FileNotFoundException e) {
logger.error("找不到文件或者文件路径错误", e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error("excel文件读取失败,失败原因:{}", e);
}
}
return null;
}
public static List<Object> readMoreThan1000Row(String filePath, Sheet sheet) {
return readMoreThan1000RowBySheet(filePath, null);
}
public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet) {
sheet = sheet != null ? sheet : initSheet;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(inputStream, sheet, excelListener);
return excelListener.getDatas();
} catch (FileNotFoundException e) {
logger.error("找不到文件或者文件路径错误");
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error("excel文件读取失败,失败原因:{}", e);
}
}
return null;
}
public static void writeExcelOneSheet1(HttpServletResponse response, List<? extends BaseRowModel> dataList, Sheet sheet, String fileName,String path) throws UnsupportedEncodingException {
if (CollectionUtils.isEmpty(dataList)) {
return;
}
if (null == sheet) {
sheet = initSheet;
}
try {
String value = "attachment; filename=" + new String(
(fileName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-disposition", value);
FileOutputStream out = new FileOutputStream(path);
ExcelWriter writer = EasyExcelFactory.getWriter(out, ExcelTypeEnum.XLSX, true);
sheet.setClazz(dataList.get(0).getClass());
writer.write(dataList, sheet);
writer.finish();
out.flush();
} catch (IOException e) {
logger.error("导出失败,失败原因:{}", e);
}
}
public static void writeExcelOneSheet2(HttpServletResponse response, List<? extends BaseRowModel> dataList, Sheet sheet, String fileName) throws UnsupportedEncodingException {
if (CollectionUtils.isEmpty(dataList)) {
return;
}
if (null == sheet) {
sheet = initSheet;
}
try {
String value = "attachment; filename=" + new String(
(fileName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-disposition", value);
ServletOutputStream out = response.getOutputStream();
ExcelWriter writer = EasyExcelFactory.getWriter(out, ExcelTypeEnum.XLSX, true);
sheet.setClazz(dataList.get(0).getClass());
writer.write(dataList, sheet);
writer.finish();
out.flush();
} catch (IOException e) {
logger.error("导出失败,失败原因:{}", e);
}
}
public static void writeExcelMutilSheetNew(HttpServletResponse response, Map<String, List<? extends BaseRowModel>> dataList, String fileName) throws UnsupportedEncodingException {
if (CollectionUtils.isEmpty(dataList)) {
return;
}
try {
String value = "attachment; filename=" + new String(
(fileName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ExcelTypeEnum.XLSX.getValue()).getBytes("gb2312"), "ISO8859-1");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-disposition", value);
ServletOutputStream out = response.getOutputStream();
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
setMutilSheet(dataList, writer);
writer.finish();
out.flush();
} catch (IOException e) {
logger.error("导出异常", e);
}
}
private static void setMutilSheet(Map<String, List<? extends BaseRowModel>> dataList, ExcelWriter writer) {
int sheetNum = 1;
for (Map.Entry<String, List<? extends BaseRowModel>> stringListEntry : dataList.entrySet()) {
Map columnWidth = new HashMap();
columnWidth.put(0, 8000);
Sheet sheet = new Sheet(sheetNum, 0, stringListEntry.getValue().get(0).getClass());
sheet.setColumnWidthMap(columnWidth);
sheet.setSheetName(stringListEntry.getKey());
writer.write(stringListEntry.getValue(), sheet);
sheetNum++;
}
}
public static void main(String[] args, HttpServletResponse response) throws UnsupportedEncodingException {
}
}
导入工具类(ExcelImportUtils):
package org.jeecg.modules.mes.utils;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
public class ExcelImportUtil {
public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) throws Exception {
ExcelListener excelListener = new ExcelListener();
ExcelReader reader = getReader(excel, excelListener);
if (reader == null) {
return null;
}
for (Sheet sheet : reader.getSheets()) {
if (rowModel != null) {
sheet.setClazz(rowModel.getClass());
}
reader.read(sheet);
}
return excelListener.getDatas();
}
public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) throws Exception {
return readExcel(excel, rowModel, sheetNo, 1);
}
public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo,
int headLineNum) throws Exception {
ExcelListener excelListener = new ExcelListener();
ExcelReader reader = getReader(excel, excelListener);
if (reader == null) {
return null;
}
reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
return excelListener.getDatas();
}
public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
String fileName, String sheetName, BaseRowModel object) {
ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
Sheet sheet = new Sheet(1, 0, object.getClass());
sheet.setSheetName(sheetName);
writer.write(list, sheet);
writer.finish();
}
private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
String filePath = fileName + ".xlsx";
File dbfFile = new File(filePath);
try {
if (!dbfFile.exists() || dbfFile.isDirectory()) {
dbfFile.createNewFile();
}
fileName = new String(filePath.getBytes(), "ISO-8859-1");
response.addHeader("Content-Disposition", "filename=" + fileName);
return response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static ExcelReader getReader(MultipartFile excel,
ExcelListener excelListener) throws Exception {
String filename = excel.getOriginalFilename();
if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
throw new Exception("文件格式错误!");
}
InputStream inputStream;
try {
inputStream = new BufferedInputStream(excel.getInputStream());
return new ExcelReader(inputStream, null, excelListener, true);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
监听工具类(ExcelListener)
package org.jeecg.modules.mes.utils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
public class ExcelListener extends AnalysisEventListener {
private List<Object> datas = new ArrayList<>();
@Override
public void invoke(Object object, AnalysisContext context) {
datas.add(object);
doSomething();
}
private void doSomething() {
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
public List<Object> getDatas() {
return datas;
}
public void setDatas(List<Object> datas) {
this.datas = datas;
}
}
StringUtil
package org.jeecg.modules.mes.utils;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
public static String parseTemplate(String template, Map properties) {
if (template == null || template.isEmpty() || properties == null) {
return template;
}
String r = "\\$\\{([^\\}]+)\\}";
Pattern pattern = Pattern.compile(r);
Matcher matcher = pattern.matcher(template);
while (matcher.find()) {
String group = matcher.group();
Object o = properties.get(group.replaceAll(r, "$1"));
if (o != null) {
template = template.replace(group, String.valueOf(o));
} else {
template = template.replace(group, "");
}
}
return template;
}
}