Java net.sf.jxls 生成模板 并导出excel

如果是 maven项目需要引入下面这个就可以

<dependency>
          <groupId>net.sf.jxls</groupId>
          <artifactId>jxls-core</artifactId>
          <version>1.0.3</version>
      </dependency>

  1. 首先应该先把模板格式定好。
  2. 将数据传输过去
  3. 遍历数据,之后再深层嵌套遍历

直接上代码

     /**
     * 导出采购订单
     */
    @RequiresPermissions("tool:gen:code")
    @BussinessLog(title = "导出采购订单", businessType = BusinessType.GENCODE)
    @GetMapping("/exportToProveExcel/{id}")
    public void exportToProveExcel(HttpServletResponse response,@PathVariable("id") String id) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String modelsPath = Global.getTemplatePath();


        PurchaseBillsEntity billsEntity = purchaseBillsService.findPurchaseBillsById(id);
        billsEntity.setPurInvs(purchaseInvsService.findPurchaseInvsByBillId(id));
        Map<String, PurchaseBillsEntity> beans = Maps.newHashMap();
        String sDate=sdf.format(billsEntity.getPurTime());
        billsEntity.setPurTime1(sDate);
        billsEntity.setExcelDetails(purchaseBillsService.collateSpecialty(billsEntity.getPurInvs()));
        beans.put("purchase", billsEntity);


        XLSTransformer transformer = new XLSTransformer();
        String xlsTemplateFileName = modelsPath+"/purchaseTemplate.xls";
        String outputFileName = "purchase-" + sdf.format(new Date()) + ".xls";

        InputStream in=null;
        OutputStream out=null;
        //设置响应
        response.setHeader("Content-Disposition", "attachment;filename=" + outputFileName);
        response.setContentType("application/vnd.ms-excel");
        try {
            in=new BufferedInputStream(new FileInputStream(xlsTemplateFileName));
            Workbook workbook=transformer.transformXLS(in, beans);
            out=response.getOutputStream();
            //将内容写入输出流并把缓存的内容全部发出去
            workbook.write(out);
            out.flush();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in!=null){try {in.close();} catch (IOException e) {}}
            if (out!=null){try {out.close();} catch (IOException e) {}}
        }
    }
 @TableField(exist = false)
    private List<ExcelPlanDetailsEntity> excelDetails;


@Data


public class ExcelPlanDetailsEntity implements  Serializable {

private  String specialty;

private List<PurchaseInvsEntity> invsEntityList; //这里直接用的是嵌套循环(每一个专业对应多个个物料)

}

下面模板会显示出来

前段点击链接 跳转的方式进行链接

 function getFilePath(id) {
        location.href =baseURL + "pos/purchaseBills/exportToProveExcel/"+id;
        opt.modal.msg('执行成功,正在生成采购订单请稍后…');
    }

posted on 2021-06-16 15:13  三千世界a  阅读(1193)  评论(1编辑  收藏  举报

导航