1.引入poi包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
2.获取模板
String filePath = request.getSession().getServletContext().getRealPath("") + "xxx.xls";
HSSFWorkbook workbook = null;
try {
//获取模板
File file = new File(filePath);
FileInputStream input = new FileInputStream(file);
workbook = new HSSFWorkbook(input);
} catch (IOException e) {
e.printStackTrace();
}
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
3.填充数据
List datas = service.getDatas();
int cellIndex = 0;
//获取最后一行
int curRowIndex = sheet.getLastRowNum();
row = sheet.createRow(curRowIndex+1):
cell = row.getCell(cellIndex++):
cell.setCellValue("第一格数据");
cell = row.getCell(cellIndex++):
cell.setCellValue("第二格数据");
cell = row.getCell(cellIndex++):
cell.setCellValue("第三格数据");
4.导出
导出有两种方式,第一是指定导出位置,第二是弹出下载
指定导出位置的导出方式:
try{
FileOutputStream output = new FileOutputStream(new File("D:\\测试.xls"));
workbook.write(ouput);
output.close();
}catch(IOException e){
e.printStackTrace();
}
弹出下载方式:
try {
String fileName = "测试.xls";
response.reset();
response.setContentType("application/msexcel");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition","attchment;filename="+new String((fileName.getBytes()),"iso-8859-1"));
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
5.前端请求
window.location.href = "xxxAction.do?action=xxx";
弹出下载不支持ajax请求,因为ajax请求的response是二进制流。