Excel有两种版本,一种是.xls类型,另一种是.xlsx类型。所以在导出的时候一定要对症下药!!!
今天主要说的是导出.xlsx类型的Excel,用到的就是Apache POI中的XSSFWorkbook,感觉炒鸡好用~
1、首先在maven项目中引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
我用的是3.17版本的,没有选那么高是因为高版本的POI中Workbook.close()方法不见了!
2、直接开写代码
public void exportEnquiryExcel(List<Student> students, HttpServletResponse response) throws Exception {
/** 行头 */
String[] sheetHeader = HeaderConstant.SHEET_HEADERS;
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
XSSFSheet sheet = xssfWorkbook.createSheet("数据模板");
/** 设置每一列的宽度 */
sheet.setColumnWidth(0, 23*256);
sheet.setColumnWidth(1, 19*256);
sheet.setColumnWidth(2, 25*256);
/** 设置高度 */
sheet.setDefaultRowHeightInPoints(14);
/** 设置样式 */
XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Font font = xssfWorkbook.createFont();
font.setBold(false);
cellStyle.setFont(font);
XSSFRow row = sheet.createRow(0);
/** 创建表头*/
for(int i = 0; i < sheetHeader.length; i ++) {
Cell cell = row.createCell(i);
cell.setCellValue(sheetHeader[i]);
cell.setCellStyle(cellStyle);
}
/** 封装数据 */
for(int i = 0; i < students.size(); i ++) {
row = sheet.createRow(i + 1);
Student student = students.get(i);
/** 学号 */
row.createCell(0).setCellValue(student.getNo());
/** 姓名 */
row.createCell(1).setCellValue(student.getName());
/** 性别 */
row.createCell(2).setCellValue(student.getSex());
}
OutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode("数据模板.xlsx", "UTF-8"));
xssfWorkbook.write(outputStream);
outputStream.flush();
outputStream.close();
xssfWorkbook.close();
}
这样就OK了