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 = new String("订单.xlsx".getBytes("gb2312"), "ISO8859-1");
    // 清空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);   // 设置列宽   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); }

  

 

 

转载于:https://www.cnblogs.com/ajya/p/9483097.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值