1.导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
2.获取导出数据
List data = 数据;
3.设置导出组件
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet名");
4.初始化sheet
HSSFRow row = sheet.createRow(0);
//设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
sheet.setColumnWidth(0, 5 * 256);
sheet.setColumnWidth(1, 15 * 256);
sheet.setColumnWidth(2, 10 * 256);
//设置为居中加粗
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setAlignment(HorizontalAlignment.CENTER);
style.setFont(font);
HSSFCell cell = row.createCell(0);
cell.setCellValue("序号");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("任务ID");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("标题");
cell.setCellStyle(style);
int rowNum = 1;
for (Object item : data) {
HSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(rowNum);
row.createCell(1).setCellValue(item.getTaskCode());
row.createCell(2).setCellValue(item.getTitle());
rowNum++;
}
5.导出
String filename = "表名.xls";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();