本文实例为大家分享了Springboot POI导出Excel的具体代码,供大家参考,具体内容如下
需求:页面根据查询条件导出(浏览器)
由于本次导出数据量较大,这里采用XSSFWorkbook多线程进行导出,注:XSSFWorkbook导出excel文件结尾为:“.xlsx”。
导出不需要返回,如有返回则会报异常!
//Controller
@RequestMapping("/stateExport")
public void stateExport(HttpServletResponse response,@RequestParam("deviceId") Long deviceId, String startTime,String endTime) {
try {
deviceMonitorService.stateExport(response, deviceId, startTime,endTime);
LOG.info("导出成功");
} catch (Exception e) {
LOG.error("导出异常:",e.getMessage());
}
}
//Service
@Override
public void stateExport(HttpServletResponse response, Long deviceId, String startTime, String endTime) throws Exception{
//list自己查询得出
List list = queryStateDetails(deviceId, startTime, endTime);
String time = TimeUtils.YEAR_DAY_SECOND_FORMAT.format(new Date());
//sheet名称
String sheetName = deviceDtls.getName() + "状态"+time;
//文件名称
String excelName = deviceDtls.getName() + "状态"+time+".xlsx";
//文件头
String[] strings = {"状态名称","开始时间","结束时间","状态时长"};
String path = this.getClass().getResource("").getPath() + "excel";
DownloadFileUtil.createDirs(path);
String filePath = path + "/" + sheetName + ".xls";
stateCreateExcel(list,strings,sheetName,excelName,filePath);
DownloadFileUtil.download(filePath, response);
}
public String stateCreateExcel(Listlist, String[] strArray,String sheetName,String excelName,String filePath)throws Exception { // 总数据条数 int dataSize = list.size(); // 线程数 int threadNum = 2; int threadSize = dataSize / threadNum; ExecutorService exec = Executors.newFixedThreadPool(threadNum); //cutList 和输入list类型保持一致 List cutList = null; // 第一步,创建一个webbook,对应一个Excel文件 XSSFWorkbook wb = new XSSFWorkbook(); // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet XSSFSheet sheet = wb.createSheet(sheetName); sheet.setDefaultColumnWidth(20);// 默认列宽 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short XSSFRow row = sheet.createRow((int) 0); // 第四步,创建单元格,并设置值表头 设置表头居中 XSSFCellStyle style = wb.createCellStyle(); // 创建一个居中格式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 添加excel title XSSFCell cell = null; for (int i = 0; i < strArray.length; i++) { cell = row.createCell((short) i); cell.setCellValue(strArray[i]); cell.setCellStyle(style); } List > tasks = new ArrayList >(); Callable task = null; // 第五步,写入实体数据 实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致 int startNum ; System.out.println("任务开始,总数:"+list.size()); // 开始时间 long start = System.currentTimeMillis(); System.out.println("线程任务执行"); for (int i = 0; i < threadNum; i++) { startNum = threadSize * i; if (i == threadNum - 1) { cutList = list.subList(threadSize * i, dataSize); } else { cutList = list.subList(threadSize * i, threadSize * (i + 1)); } //listStr 和输入list类型保持一致 final List listStr = cutList; int finalStartNum = startNum; task = new Callable () { final int s= finalStartNum; @Override public Integer call() throws Exception { for(int j=0;j > results = exec.invokeAll(tasks); } catch (Exception e) { e.printStackTrace(); } // 关闭线程池 exec.shutdown(); DownloadFileUtil.delfile(filePath); // 第六步,将文件存到指定位置 try { FileOutputStream fout = new FileOutputStream(filePath); wb.write(fout); fout.flush(); fout.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("线程任务执行结束"); System.err.println("执行任务消耗了 :" + (System.currentTimeMillis() - start) + "毫秒"); return filePath; }
//线程同步,保证不会多插入数据
private synchronized XSSFRow getRow(XSSFSheet sheet, int rownum) {
//如果不包含列头,+1去掉即可
return sheet.createRow(rownum+1);
}
最后附上使用的工具类
package com.sec.deviceband.utils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
public class DownloadFileUtil {
public static void createDirs(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
public static void download(String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ URLEncoder.encode(filename, "utf-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=utf-8");
toClient.write(buffer);
toClient.flush();
toClient.close();
delfile(path);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void delfile(String filepath) {
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
}
}
测试方式:浏览器输入请求路径
测试效果:
由于水平有限,博客中难免会有一些错误,有纰漏之处恳请各位大佬不吝赐教!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



