poi导出Excel直接在浏览器下载

时间:2022-03-02 09:04:32

需求:导出成Excel格式,要在浏览器看到类似于下载的效果。

导出的Excel和下载在同一个目录下。

xxController.java

// 导出
@RequestMapping(value = "/createExcelToDisk", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
public @ResponseBody String createExcelToDisk(HttpServletResponse response,List<Object>valueList,) throws IOException, IllegalAccessException, ClassNotFoundException {
response.reset(); // 清除buffer缓存
// 指定下载的文件名
response.setHeader("Content-Disposition", "attachment;filename=contacts" + CurrentTime.getDateTime() + ".xlsx");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
XSSFWorkbook workbook = null;
try {
workbook = ExcelUtils.exportContacts(valueList);
OutputStream output;
try {
output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
bufferedOutPut.flush();
workbook.write(bufferedOutPut);
bufferedOutPut.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
ExcelUtils.java 
package com.ky.lm.util.common;

import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtils { public static XSSFWorkbook exportContacts(List<Object> valueList)
throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
XSSFWorkbook xssfWorkbook = null;
String sheetName = "客户列表";
xssfWorkbook = createExcelFile(valueList, sheetName);
return xssfWorkbook;
} public static XSSFWorkbook createExcelFile(List<Object> valueList, String sheetName)
throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
// 创建新的Excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
XSSFSheet sheet = workbook.createSheet(sheetName);
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("姓名");
cell = row.createCell(1);
cell.setCellValue("年龄");
for (int i = 0; i < valueList.size(); i++) {
row = sheet.createRow((int) i + 1);
row.createCell(i).setCellValue(valueList[i]);
}
return workbook;
} }

效果

poi导出Excel直接在浏览器下载

这里补充一个要点:导出直接在浏览器下载这样的格式    !!不支持ajax!!  最好用a标签来写。

有什么不明白的可以在评论里提问哦 ^ - ^ !