public class ExcelUtil {
/**
* @param beans Map<String, Object>,数据集合
* @param path String,模板路径
* @param fileName String,文件名
* @param response HttpServletResponse
* @Title: exportExcel
* @Description: 导出Excel执行方法
*/
public static void exportExcel(Map<String, Object> beans, String path, String fileName,
HttpServletResponse response) {
FileInputStream fileInputStream = null;
OutputStream outputStream = null;
XLSTransformer transformer = new XLSTransformer();
try {
// 文件名称
fileName = fileName + "_" + DateUtil.format(new Date(), DateUtil.PATTERN[4]) + ".xls";
// 获得写入文件名称的OutputStream
response.setContentType("application/x-excel");
response.setHeader("Content-Disposition", "attachment;filename=".concat(new String(fileName.getBytes
("GB2312"), "ISO-8859-1")));
outputStream = response.getOutputStream();
//获取模板路径
File file = ResourceUtils.getFile("classpath:template_excel");
// 获得模板的输入流
fileInputStream = new FileInputStream(file + "/" + path);
// 将beans通过模板输入流写到workbook中
Workbook workbook = transformer.transformXLS(fileInputStream, beans);
workbook.write(outputStream);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param file MultipartFile,上传的文件
* @param xmlConfig String,xml路径
* @param clazz Class<T>
* @return List<T>
* @Title: exportExcel
* @Description: 导入Excel执行方法
*/
public static <T> List<T> importExcel(MultipartFile file, String xmlConfig, String listKey, Class<T> clazz) {
InputStream inputXLS = null;
InputStream inputXML = null;
try {
inputXML = clazz.getClass().getResourceAsStream(xmlConfig);
XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML);
inputXLS = new BufferedInputStream(file.getInputStream());
List<T> list = new ArrayList<>();
Map<String, Object> beans = new HashMap<>();
beans.put(listKey, list);
XLSReadStatus readStatus = mainReader.read(inputXLS, beans);
if (readStatus.isStatusOK()) {
return list;
}
} catch (IOException | SAXException | InvalidFormatException e) {
e.printStackTrace();
} finally {
try {
if (inputXML != null) {
inputXML.close();
}
if (inputXLS != null) {
inputXLS.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
jxls导入导出工具类
最新推荐文章于 2024-02-09 18:03:54 发布