Java导出excel文件的两种方法

在项目中生成临时文件的方法  

Config.inReceiptFilePath.getValue()//文件路径

/**
 * 导出入库单详情
 * @param inReceiptId   入库单id
 * @param response
 * @param request
 * @throws Exception
 */
@RequestMapping("exportInReceipt")
@ResponseBody
public void exportPriceList(Integer inReceiptId, HttpServletResponse response, HttpServletRequest request) throws Exception {
   List<IotCard> iotCards = cardService.selectByInReceiptId(inReceiptId);
   IotInReceipt iotInReceipt = inReceiptService.selectById(inReceiptId);
   FileOutputStream outputStream = null;
   String tableName = "入库单明细";
   String filePath = Config.inReceiptFilePath.getValue() + File.separator/*+adminUser.getAdminName()*/ + "-"+iotInReceipt.getSerialNum()+ "-" + DateUtil.Date2String(new Date(), "yyyy-MM-dd") + tableName + ".xls";
   String showFileName = iotInReceipt.getSerialNum()+ "-" + DateUtil.Date2String(new Date(), "yyyy-MM-dd") + tableName + ".xls";
   try {
      //创建一个Excel工作簿对象
      outputStream = new FileOutputStream(filePath);
      //创建一个Excel工作簿对象
      HSSFWorkbook workbook = new HSSFWorkbook();
      //创建一个合并单元格做为表头根据下标合并单元格
      CellRangeAddress c1 = new CellRangeAddress(0, 0, 0, 9);
      //得到Excel工作表对象(sheet的名字为title的值)
      HSSFSheet sheet = workbook.createSheet(tableName);
      //创建单元格样式
      HSSFCellStyle style1 = workbook.createCellStyle();
      style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
      style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
      //创建字体样式
      HSSFFont font1 = workbook.createFont();
      font1.setFontHeightInPoints((short) 18);
      //把字体赋予样式
      style1.setFont(font1);
      //创建单元格样式
      HSSFCellStyle style2 = workbook.createCellStyle();
      style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
      style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
      //创建字体样式
      HSSFFont font2 = workbook.createFont();
      font2.setFontHeightInPoints((short) 12);
      //把字体赋予样式
      style2.setFont(font2);
      //将创建好的单元格赋予表1
      sheet.addMergedRegion(c1);
      //获取第一行
      HSSFRow row1 = sheet.createRow(0);
      //获取第一行中的第一个单元格
      HSSFCell cell = row1.createCell(0);
      //把样式赋予单元格
      cell.setCellStyle(style1);
      cell.setCellValue(iotInReceipt.getSerialNum() + "入库单明细");
      HSSFRow row2 = sheet.createRow(1);
      String[] titles = {"ICCID", "MSISDN", "运营商", "流量套餐", "供应商", "入库时间"};
      for (int i = 0; i < titles.length; i++) {
         String title = titles[i];
         HSSFCell cell2 = row2.createCell(i);
         cell2.setCellStyle(style2);
         cell2.setCellValue(title);

      }
      for (int j = 0; j < iotCards.size(); j++) {
         //输出list
         IotCard  card = iotCards.get(j);
         HSSFRow row = sheet.createRow(j + 2);
         HSSFCell cc1 = row.createCell(0);
         cc1.setCellValue(card.getIccid());
         HSSFCell cc2 = row.createCell(1);
         cc2.setCellValue(card.getMsisdn());
         HSSFCell cc3 = row.createCell(2);
         cc3.setCellValue(card.getOperatorLiteral());
         HSSFCell cc4 = row.createCell(3);
         cc4.setCellValue(card.getProductName());
         HSSFCell cc5 = row.createCell(4);
         cc5.setCellValue(card.getSupplyName());
         HSSFCell cc6 = row.createCell(5);
         cc6.setCellValue(card.getCreateTime().substring(0,19));
      }
      workbook.write(outputStream);

      FileUtil.downloadFile(response,filePath,showFileName);
   } catch (Exception e) {
      logger.error(e.getMessage(), e);
   } finally {
      try {
         if(outputStream != null) {
            outputStream.close();
         }
      } catch (Exception e) {
         logger.error(e.getMessage(), e);
      }
   }
}
 

直接输出  不在项目中生成临时文件的方法

/**
 * 导出入库单详情
 * @param inReceiptId   入库单id
 * @param response
 * @param request
 * @throws Exception
 */
@RequestMapping("exportInReceipt")
@ResponseBody
public void exportPriceList(Integer inReceiptId, HttpServletResponse response, HttpServletRequest request) throws Exception {
   List<IotCard> iotCards = cardService.selectByInReceiptId(inReceiptId);
   IotInReceipt iotInReceipt = inReceiptService.selectById(inReceiptId);
   OutputStream os = response.getOutputStream();// 取得输出流
   String tableName = "入库单明细";
   String showFileName = iotInReceipt.getSerialNum()+ "-" + DateUtil.Date2String(new Date(), "yyyy-MM-dd") + tableName + ".xls";
   try {
      //创建一个Excel工作簿对象
      HSSFWorkbook workbook = new HSSFWorkbook();
      //创建一个合并单元格做为表头根据下标合并单元格
      CellRangeAddress c1 = new CellRangeAddress(0, 0, 0, 9);
      //得到Excel工作表对象(sheet的名字为title的值)
      HSSFSheet sheet = workbook.createSheet(tableName);
      //创建单元格样式
      HSSFCellStyle style1 = workbook.createCellStyle();
      style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
      style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
      //创建字体样式
      HSSFFont font1 = workbook.createFont();
      font1.setFontHeightInPoints((short) 18);
      //把字体赋予样式
      style1.setFont(font1);
      //创建单元格样式
      HSSFCellStyle style2 = workbook.createCellStyle();
      style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
      style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
      //创建字体样式
      HSSFFont font2 = workbook.createFont();
      font2.setFontHeightInPoints((short) 12);
      //把字体赋予样式
      style2.setFont(font2);
      //将创建好的单元格赋予表1
      sheet.addMergedRegion(c1);
      //获取第一行
      HSSFRow row1 = sheet.createRow(0);
      //获取第一行中的第一个单元格
      HSSFCell cell = row1.createCell(0);
      //把样式赋予单元格
      cell.setCellStyle(style1);
      cell.setCellValue(iotInReceipt.getSerialNum() + "入库单明细");
      HSSFRow row2 = sheet.createRow(1);
      String[] titles = {"ICCID", "MSISDN", "运营商", "流量套餐", "供应商", "入库时间"};
      for (int i = 0; i < titles.length; i++) {
         String title = titles[i];
         HSSFCell cell2 = row2.createCell(i);
         cell2.setCellStyle(style2);
         cell2.setCellValue(title);

      }
      for (int j = 0; j < iotCards.size(); j++) {
         //输出list
         IotCard  card = iotCards.get(j);
         HSSFRow row = sheet.createRow(j + 2);
         HSSFCell cc1 = row.createCell(0);
         cc1.setCellValue(card.getIccid());
         HSSFCell cc2 = row.createCell(1);
         cc2.setCellValue(card.getMsisdn());
         HSSFCell cc3 = row.createCell(2);
         cc3.setCellValue(card.getOperatorLiteral());
         HSSFCell cc4 = row.createCell(3);
         cc4.setCellValue(card.getProductName());
         HSSFCell cc5 = row.createCell(4);
         cc5.setCellValue(card.getSupplyName());
         HSSFCell cc6 = row.createCell(5);
         cc6.setCellValue(card.getCreateTime().substring(0,19));
      }
      response.reset();// 清空输出流
      response.setHeader("Content-disposition", "attachment; filename="
            + showFileName + ".xls"); // 设定输出文件头,该方法有两个参数,分别表示应答头的名字和值。
      response.setContentType("application/msexcel");
      workbook.write(os);
   } catch (Exception e) {
      logger.error(e.getMessage(), e);
   } finally {
      try {
         if(os != null) {
            os.close();
         }
      } catch (Exception e) {
         logger.error(e.getMessage(), e);
      }
   }
}




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,针对你的问题,我可以给出以下两种情况下导出Excel方法: 1. 使用Apache POI库 Apache POI是一个Java库,可以处理Microsoft Office格式的文件,包括Excel。如果你的实体类是基于JavaBean规范的,那么可以使用Apache POI来导出Excel文件。 首先,你需要将实体类的属性与Excel表格中的列一一对应,定义一个数据模型。然后,使用Apache POI的API将数据写入Excel文件中。 以下是一个基于Apache POI的示例代码: ```java public void exportExcel(List<Book> bookList, OutputStream outputStream) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Book List"); // 创建表头 HSSFRow headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("Book ID"); headerRow.createCell(1).setCellValue("Title"); headerRow.createCell(2).setCellValue("Author"); headerRow.createCell(3).setCellValue("Price"); // 填充数据 int rowNum = 1; for (Book book : bookList) { HSSFRow row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(book.getId()); row.createCell(1).setCellValue(book.getTitle()); row.createCell(2).setCellValue(book.getAuthor()); row.createCell(3).setCellValue(book.getPrice()); } // 输出Excel文件 try { workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } } ``` 2. 使用EasyExcel库 EasyExcel是一个基于阿里巴巴开发的Java库,可以方便地导入和导出Excel文件。如果你的实体类是基于Java Bean规范的,那么可以使用EasyExcel导出Excel文件。 以下是一个基于EasyExcel的示例代码: ```java public void exportExcel(List<Book> bookList, OutputStream outputStream) { List<BookDTO> bookDTOList = bookList.stream().map(BookDTO::new).collect(Collectors.toList()); ExcelWriter excelWriter = EasyExcel.write(outputStream, BookDTO.class).build(); WriteSheet writeSheet = EasyExcel.writerSheet("Book List").build(); excelWriter.write(bookDTOList, writeSheet); excelWriter.finish(); } ``` 在这个示例代码中,我们先将Book实体类转换为BookDTO数据传输对象,然后使用EasyExcel的API将数据写入Excel文件中。注意,EasyExcel的API比Apache POI更加简洁易用,但是可能会比较耗费内存。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值