apache poi的使用

第一步:首先引入依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>${poi.version}</version>
</dependency>

其实本质上还是去导入相关的jar包,用来封装数据(版本根据自己实际情况进行决定)

第二步:我以最近刚写的vcanbuy的项目中导出会员交易列表来举例!

直接上代码

@RequestMapping(value = "sellerOrder/excelTradeList")
public void getExcelTradeList(
      @RequestParam(defaultValue = Constants.PAGENUM) int pageNum,
      @RequestParam(defaultValue = Constants.PAGESIZE) int pageSize, HttpServletRequest request, HttpServletResponse response) {
   Page<TradeVo1> page = tradeManager.getTradeList(pageNum, pageSize);
   List<TradeVo1> list=page.getlist();
   // 创建excel
   HSSFWorkbook wk = new HSSFWorkbook();
   // 创建一张工作表
   HSSFSheet sheet = wk.createSheet("会员管理");
   // 设置列宽
   sheet.setColumnWidth(0, 5000);
   // 创建第一行
   HSSFRow row = sheet.createRow(0);
   row.createCell(0).setCellValue("客户信息");
   row.createCell(1).setCellValue("会员积分");
   row.createCell(2).setCellValue("交易总额");
   row.createCell(3).setCellValue("交易笔数");
   row.createCell(4).setCellValue("平均交易金额");
   row.createCell(5).setCellValue("上次交易时间");
   for (TradeVo1 tradeVo1: list) {
      HSSFRow dataRow=sheet.createRow(sheet.getLastRowNum()+1);
      dataRow.createCell(0).setCellValue(tradeVo1.getAccount());
      dataRow.createCell(1).setCellValue(tradeVo1.getPoint()+","+tradeVo1.getGrade());
      dataRow.createCell(2).setCellValue(tradeVo1.getTotalTransction()+"");
      dataRow.createCell(3).setCellValue(tradeVo1.getCountTransction()+"");
      dataRow.createCell(4).setCellValue(tradeVo1.getAvgTransction()+"");
      dataRow.createCell(5).setCellValue(DateUtils.yyyy_MM_dd(tradeVo1.getGmtCreate()));
   }
   // 保存到本地
   // 关闭工作薄
   try {
      String filename="会员管理.xls";
      String agent=request.getHeader("user-agent");
      filename= encodeDownloadFilename(filename,agent);
      response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
      response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
      wk.write(response.getOutputStream());
      wk.close();
   } catch (Exception e) {
      e.printStackTrace();
   }

}
这里我对
encodeDownloadFilename(filename,agent)详解一下,它的作用是用来
下载文件时,针对不同浏览器,进行附件名的编码
/**
 * 下载文件时,针对不同浏览器,进行附件名的编码
 *
 * @param filename
 *            下载文件名
 * @param agent
 *            客户端浏览器
 * @return 编码后的下载附件名
 * @throws IOException
 */
public static String encodeDownloadFilename(String filename, String agent)
      throws IOException {
   if (agent.contains("Firefox")) { // 火狐浏览器
      filename = "=?UTF-8?B?"
            + new BASE64Encoder().encode(filename.getBytes("utf-8"))
            + "?=";
      filename = filename.replaceAll("\r\n", "");
   } else { // IE及其他浏览器
      filename = URLEncoder.encode(filename, "utf-8");
      filename = filename.replace("+"," ");
   }
   return filename;
}

这样poi导入excel就已经完成了!

猜你喜欢

转载自blog.csdn.net/weixin_41247813/article/details/81603396