java导出Excel
加入pom依赖: <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>RELEASE</version>
</dependency>
下载Excel:
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
// HSSFWorkbook workbook = new HSSFWorkbook();
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建一个Excel表单,参数为sheet的名字
XSSFSheet sheet = workbook.createSheet();
// 创建表头
setTitle(workbook, sheet);
// 新增数据行,并且设置单元格数据
int rowNum = 1;
for (Map<String, Object> answer : answerList) {
XSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(answer.get("totalAmount").toString());
row.createCell(1).setCellValue(answer.get("generationTime").toString());
row.createCell(2).setCellValue(answer.get("username").toString());
rowNum++;
}
String fileName = "orders.xlsx";
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
// 将excel写入到输出流中
workbook.write(os);
System.out.println(os);
os.flush();
os.close();
}
设置表头:
private void setTitle(XSSFWorkbook workbook, XSSFSheet sheet) {
XSSFRow row = sheet.createRow(0);
// 设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
sheet.setColumnWidth(0, 20 * 256);
sheet.setColumnWidth(1, 20 * 256);
sheet.setColumnWidth(2, 20 * 256);
// 设置为居中加粗
XSSFCellStyle style = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setBold(true);
style.setFont(font);
XSSFCell 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);
}
上一篇: NEC拟6年内使人工智能业务收入达到2500亿日元
下一篇: 电视台表结构