Poi依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
controller
设置表头:
/***
* 创建表头
* @param workbook
* @param sheet
*/
private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet) {
HSSFRow row = sheet.createRow(0);
//设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
sheet.setColumnWidth(2, 12 * 256);
sheet.setColumnWidth(3, 17 * 256);
//设置为居中加粗
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setFont(font);
HSSFCell cell;
cell = row.createCell(0);
cell.setCellValue("序号");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("金额");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("描述");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("日期");
cell.setCellStyle(style);
}
导出数据
/***
* 获取excel数据
* @return 返回文件名称及excel文件的URL
* @throws IOException
*/
@SuppressWarnings({"unchecked", "rawtypes"})
@GetMapping(value = "/downloadExcel")
public void getExcel() throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("统计表");
createTitle(workbook, sheet);
List<StatisticsInfo> entities = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
StatisticsInfo item = new StatisticsInfo("name", i);
item.setId(i);
entities.add(item);
}
//设置日期格式
HSSFCellStyle style = workbook.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//新增数据行,并且设置单元格数据
int rowNum = 1;
for (StatisticsInfo statisticsInfo : entities) {
HSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(statisticsInfo.getId());
row.createCell(1).setCellValue(statisticsInfo.getAge());
row.createCell(2).setCellValue(statisticsInfo.getName());
rowNum++;
}
File savefile = new File("e:/");
if (!savefile.exists()) {
savefile.mkdirs();
}
FileOutputStream fos = new FileOutputStream("e:/tt.xls");
workbook.write(fos);
fos.close();
}
测试下载页面
<input type="button" value="导出为Excel" onclick="window.open('/downloadExcel');"/>