java 实现 excel 自定义样式和字段导出

这篇具有很好参考价值的文章主要介绍了java 实现 excel 自定义样式和字段导出。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

 java 功能中,有一个功能是大家经常做的,就是excel导出,简单的excel导出 可以直接用阿里的easyExcel添加注解自动导出来某些固定字段就行了,这个是比较简单的导出,本文就不作过多赘述
 这篇文章主要是针对,某些页面的导出,比如说按照页面上的表格的样式导出数据 类似于下面图片这样的,主要应用于报表,自定义的样式之类的excel导出 本文导出 总汇,标品,定开三个sheet的数据,有则导出,无则不用导出

导出的excel需要的pom结构


最后导出的请求接口字段
java导出excel样式设置,excel,java,maven,spring boot

  最后导出的内容如下
java导出excel样式设置,excel,java,maven,spring boot

 

    <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>



java导出excel样式设置,excel,java,maven,spring boot
 

 1 第一步 控制层

 

    /**
     * 根据报价单id导出报表
     *
     * @param response
     * @param id
     */
    @PostMapping("/exportPriceDetail/{id}")
    @ApiOperation(value = "根据报价单id导出报表")
    @SneakyThrows
    public void exportPriceDetail(HttpServletResponse response, @PathVariable("id") Long id, @RequestBody List<ExportMenuReq> menus) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodeFileName = URLEncoder.encode("报价单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodeFileName + ".xlsx");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        priceDetailExportService.exportPriceDetail(response, id,menus);
    }

2.第二步 逻辑层
 主要生成水印和处理要导出的,模块的逻辑
 文章来源地址https://www.toymoban.com/news/detail-699085.html

    @SneakyThrows
    public void exportPriceDetail(HttpServletResponse response, Long id, List<ExportMenuReq> menus) {
        UserDTO user = AuthenticationContext.getUser();
        Watermark watermark = new Watermark();
        watermark.setContent(user.getUserAccount()+"@XX集团"+user.getErpId());
        watermark.setWidth(500);
        watermark.setHeight(200);
        watermark.setYAxis(200);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).inMemory(true).registerWriteHandler(new CustomerWaterMarkHandler(watermark)).build();
        List<String> sheetNames = new ArrayList<>();
        Map<String, List<String>> openContentColumnNames = new HashMap<>();
        Map<String, List<String>> openContentDevelopmentColumnNames = new HashMap<>();
        for (ExportMenuReq menu : menus) {
            sheetNames.add(menu.getName());
            if (CollectionUtils.isNotEmpty(menu.getChildren())) {
                List<String> columnNames = openContentColumnNames.get(menu.getName()) != null ? openContentColumnNames.get(menu.getName()) : new ArrayList<String>();
                List<ExportMenuReq> openContents = menu.getChildren();
                for (ExportMenuReq openContent : openContents) {
                    if (Constants.DEVELOPMENT_INFO.equals(openContent.getName()) && CollectionUtils.isNotEmpty(openContent.getChildren())) {
                        List<ExportMenuReq> developmentColumns = openContent.getChildren();
                        List<String> developmentColumnNames = developmentColumns.stream().map(tree -> tree.getName() + Constants.DEVELOPMENT_SUFFIX).collect(Collectors.toList());
                        columnNames.addAll(developmentColumnNames);
                        openContentDevelopmentColumnNames.put(menu.getName(), developmentColumnNames);
                    } else {
                        columnNames.add(openContent.getName());
                    }
                }
                //根据ID获取列,如果用名称遇到名称一样的数据,就会因为key一样导致只有一个列表,并且两个列表value都放入一个key
                openContentColumnNames.put(menu.getId().toString(), columnNames);
            }
        }
        exportPriceDetail(id, sheetNames, openContentColumnNames, openContentDevelopmentColumnNames, excelWriter);
    }
2.1 writeCollectInfo()方法,组装总汇的导出数据

 private void writeCollectInfo(CollectInfoVo collectInfoVo, ExcelWriter excelWriter) {
        if (collectInfoVo == null) {
            return;
        }
        WriteSheet writeSheet = EasyExcel.writerSheet("总汇").build();
        int tableNo = 0;
        Integer headSize = 9;
        //有效期
        String priceDataInfo = getPriceDataInfo(collectInfoVo.getPriceData(), collectInfoVo.getExpirationDay());
        ContactInfoExcelVO priceDataInfoVO = ContactInfoExcelVO.builder()
                .contactInfo(priceDataInfo)
                .build();
        WriteTable priceDataInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.FALSE).registerWriteHandler(new ColumnMergeStrategy(0, headSize - 1)).head(ContactInfoExcelVO.class).build();
        excelWriter.write(Arrays.asList(priceDataInfoVO), writeSheet, priceDataInfoTable);

        //标题
        Map<String, String> params = new HashMap<>();
        String priceName = StringUtils.isNotBlank(collectInfoVo.getPriceName()) ? collectInfoVo.getPriceName() : "报价单";
        params.put("priceName", priceName);
        WriteTable priceNameTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new HeadWriteHandler(params)).head(PriceBillBaseExcelVO.class).build();
        excelWriter.write(Collections.emptyList(), writeSheet, priceNameTable);

        //联系人信息
        String contactInfo = String.format("联系人: %s\r\n联系方式: %s", StringUtils.trimToEmpty(collectInfoVo.getContactName()), StringUtils.trimToEmpty(collectInfoVo.getMobile()));
        ContactInfoExcelVO contactInfoExcelVO = ContactInfoExcelVO.builder()
                .contactInfo(contactInfo)
                .build();
        WriteTable contactInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.FALSE).registerWriteHandler(new ColumnMergeStrategy(0, headSize - 1)).head(ContactInfoExcelVO.class).build();
        excelWriter.write(Arrays.asList(contactInfoExcelVO), writeSheet, contactInfoTable);

        //最后三列显示小计
        Integer lastCol = headSize - 5;
        //标品
        StandardInfoVO standardInfo = collectInfoVo.getStandardInfo();
        if (standardInfo != null && CollectionUtils.isNotEmpty(standardInfo.getStandards())) {
            List<StandardVO> standards = standardInfo.getStandards();
            List<StandardExcelVO> standardExcelVOS = standards.stream().map(standInfoConverter::toExcel).collect(Collectors.toList());
            standardExcelVOS.stream().forEach(standard -> {
                // 设置功能清单
                if (StringUtils.isNotBlank(standard.getProductListUrl())) {
                    WriteCellData<String> hyperlink = new WriteCellData<>("点击查看");
                    HyperlinkData hyperlinkData = new HyperlinkData();
                    hyperlinkData.setAddress(standard.getProductListUrl());
                    hyperlinkData.setHyperlinkType(HyperlinkData.HyperlinkType.URL);
                    hyperlink.setHyperlinkData(hyperlinkData);
                    standard.setProductListUrlHyperlink(hyperlink);
                }
            });
            WriteTable standardTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).head(StandardExcelVO.class).build();
            excelWriter.write(standardExcelVOS, writeSheet, standardTable);
            //小计
            //最后三列显示小计
            writeSubtotal(excelWriter, writeSheet, standardInfo.getTaxPrice(), standardInfo.getTaxUpperPrice(), standardInfo.getNotTaxTotalPrice(), standardInfo.getNotTaxTotalUpperPrice(), lastCol, tableNo++);
        }
        //第三方产品
        TripartiteCollectVO priceTripartiteInfo = collectInfoVo.getPriceTripartiteInfo();
        if (priceTripartiteInfo != null && priceTripartiteInfo.getTripartiteInfoVOS() != null) {
            List<TripartiteInfoVO> tripartiteInfo = priceTripartiteInfo.getTripartiteInfoVOS();
            List<TripartiteInfoExcelVO> tripartiteInfoExcelList = tripartiteInfo.stream().map(tripartiteInfoConvert::toExcel).collect(Collectors.toList());
            // 设置功能清单
            tripartiteInfoExcelList.stream().forEach(tripartiteInfoExcelVO -> {
                // 设置功能清单
                if (StringUtils.isNotBlank(tripartiteInfoExcelVO.getProductListUrl())) {
                    WriteCellData<String> hyperlink = new WriteCellData<>("点击查看");
                    HyperlinkData hyperlinkData = new HyperlinkData();
                    hyperlinkData.setAddress(tripartiteInfoExcelVO.getProductListUrl());
                    hyperlinkData.setHyperlinkType(HyperlinkData.HyperlinkType.URL);
                    hyperlink.setHyperlinkData(hyperlinkData);
                    tripartiteInfoExcelVO.setProductListUrlHyperlink(hyperlink);
                }
            });

            WriteTable tripartiteInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE)
                    .head(TripartiteInfoExcelVO.class).build();
            excelWriter.write(tripartiteInfoExcelList, writeSheet, tripartiteInfoTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, priceTripartiteInfo, lastCol, tableNo++);
        }

        //定开
        OpeningCollectVO openingInfo = collectInfoVo.getOpeningInfo();
        if (openingInfo != null && CollectionUtils.isNotEmpty(openingInfo.getOpeningVOS())) {
            List<OpeningVO> openingVOS = openingInfo.getOpeningVOS();
            List<OpeningExcelVO> openingExcelVOS = openingVOS.stream().map(openingConverter::toExcel).collect(Collectors.toList());
            WriteTable openingTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new ColumnMergeStrategy(7, 8)).head(OpeningExcelVO.class).build();
            excelWriter.write(openingExcelVOS, writeSheet, openingTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, openingInfo, lastCol, tableNo++);
        }

        // 运维管理费
        ServiceInfoCollectVO serviceInfo = collectInfoVo.getServiceInfo();
        if (serviceInfo != null && serviceInfo.getServiceInfoVO() != null) {
            ServiceInfoVO serviceInfoVO = serviceInfo.getServiceInfoVO();
            ServiceInfoExcelVO serviceInfoExcelVO = serviceInfoConvert.toExcel(serviceInfoVO);
            WriteTable serviceInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new ColumnMergeStrategy(0, 1))
                    .registerWriteHandler(new ColumnMergeStrategy(7, 8)).head(ServiceInfoExcelVO.class).build();
            excelWriter.write(Arrays.asList(serviceInfoExcelVO), writeSheet, serviceInfoTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, serviceInfo, lastCol, tableNo++);
        }

        //服务器费用
        ServerInfoCollectVO serverInfo = collectInfoVo.getServerInfo();
        if (serverInfo != null && CollectionUtils.isNotEmpty(serverInfo.getServerInfoVOS())) {
            List<ServerInfoVO> serverInfos = serverInfo.getServerInfoVOS();
            List<ServerInfoExcelVO> serverInfoExcelVOS = serverInfos.stream().map(serverInfoConvert::toExcel).collect(Collectors.toList());
            WriteTable serverInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new ColumnMergeStrategy(0, 1))
                    .registerWriteHandler(new ColumnMergeStrategy(7, 8)).head(ServerInfoExcelVO.class).build();
            excelWriter.write(serverInfoExcelVOS, writeSheet, serverInfoTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, serverInfo, lastCol, tableNo++);
        }

        //项目管理费
        ManagementInfoCollectVO managementInfoVO = collectInfoVo.getManagementInfo();
        if (managementInfoVO != null && managementInfoVO.getManagementInfoVO() != null) {
            ManagementInfoVO managementInfo = managementInfoVO.getManagementInfoVO();
            ManagementInfoExcelVO managementInfoExcelVO = managementInfoConvert.toExcel(managementInfo);
            WriteTable managementInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new ColumnMergeStrategy(0, 1))
                    .registerWriteHandler(new ColumnMergeStrategy(7, 8)).registerWriteHandler(new ColumnMergeStrategy(2, 3)).head(ManagementInfoExcelVO.class).build();
            excelWriter.write(Arrays.asList(managementInfoExcelVO), writeSheet, managementInfoTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, managementInfoVO, lastCol, tableNo++);
        }


        //项目驻场费
        ResidentInfoCollectVO residentInfo = collectInfoVo.getResidentInfo();
        if (residentInfo != null && CollectionUtils.isNotEmpty(residentInfo.getResidentInfoVOS())) {
            List<ResidentInfoVO> residentInfos = residentInfo.getResidentInfoVOS();
            List<ResidentInfoExcelVO> residentInfoExcelVOS = residentInfos.stream().map(residentInfoConvert::toExcel).collect(Collectors.toList());
            WriteTable residentInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new ColumnMergeStrategy(0, 1))
                    .registerWriteHandler(new ColumnMergeStrategy(7, 8)).head(ResidentInfoExcelVO.class).build();
            excelWriter.write(residentInfoExcelVOS, writeSheet, residentInfoTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, residentInfo, lastCol, tableNo++);
        }


        //项目差旅费
        TravelChargeInfoCollectVO travelChargeInfo = collectInfoVo.getTravelChargeInfo();
        if (travelChargeInfo != null && CollectionUtils.isNotEmpty(travelChargeInfo.getTravelChargeInfoVOS())) {
            List<TravelChargeInfoVO> travelChargeInfos = travelChargeInfo.getTravelChargeInfoVOS();
            List<TravelChargeInfoExcelVO> travelChargeInfoExcelVOS = travelChargeInfos.stream().map(travelChargeInfoConvert::toExcel).collect(Collectors.toList());
            WriteTable travelChargeInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new ColumnMergeStrategy(0, 1))
                    .registerWriteHandler(new ColumnMergeStrategy(7, 8)).head(TravelChargeInfoExcelVO.class).build();
            excelWriter.write(travelChargeInfoExcelVOS, writeSheet, travelChargeInfoTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, travelChargeInfo, lastCol, tableNo++);
        }
        //培训管理费
        TrainModuleCollectVO trainModuleInfo = collectInfoVo.getTrainModuleInfo();
        if (trainModuleInfo != null && CollectionUtils.isNotEmpty(trainModuleInfo.getTrainModuleVOS())) {
            List<TrainModuleVO> trainModuleInfos = trainModuleInfo.getTrainModuleVOS();
            List<TrainModuleExcelVO> trainModuleExcelVOS = trainModuleInfos.stream().map(trainModuleConvert::toExcel).collect(Collectors.toList());
            WriteTable trainModuleTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).registerWriteHandler(new ColumnMergeStrategy(0, 1))
                    .registerWriteHandler(new ColumnMergeStrategy(7, 8)).registerWriteHandler(new ColumnMergeStrategy(2, 3)).head(TrainModuleExcelVO.class).build();
            excelWriter.write(trainModuleExcelVOS, writeSheet, trainModuleTable);
            //小计
            writeSubtotal(excelWriter, writeSheet, trainModuleInfo, lastCol, tableNo++);
        }
        //写空行
        WriteTable newLineInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.FALSE).registerWriteHandler(new ColumnMergeStrategy(0, 8)).head(TravelChargeInfoExcelVO.class).build();
        excelWriter.write(Arrays.asList(""), writeSheet, newLineInfoTable);

        //写服务费用
        writeServiceTax(excelWriter, writeSheet, collectInfoVo,tableNo++);

        //写空行
        excelWriter.write(Arrays.asList(""), writeSheet, newLineInfoTable);

        //写总计
        //计算折后价
        BigDecimal totalDiscountPrice = collectInfoVo.getTaxTotalPrice() != null ? new BigDecimal(collectInfoVo.getTaxTotalPrice()) : new BigDecimal("0");
        if (collectInfoVo.getTaxTotalPrice() != null && collectInfoVo.getPriceDiscount() == null && collectInfoVo.getDiscountTotalPrice() == null) {
            totalDiscountPrice = new BigDecimal(collectInfoVo.getTaxTotalPrice());
        } else if (collectInfoVo.getTaxTotalPrice() != null && collectInfoVo.getPriceDiscount() != null) {
            totalDiscountPrice = new BigDecimal(collectInfoVo.getTaxTotalPrice()).multiply(collectInfoVo.getPriceDiscount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        } else if (collectInfoVo.getDiscountTotalPrice() != null) {
            totalDiscountPrice = new BigDecimal(collectInfoVo.getDiscountTotalPrice());
        }
        String totalUpperDiscountPrice = NumberChineseFormatter.format(totalDiscountPrice.divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP).doubleValue(),
                true,
                true);
        writeSummaryTotal(excelWriter, writeSheet, collectInfoVo, totalDiscountPrice, totalUpperDiscountPrice, tableNo++);
    }
2.1导出的表格模块比较多,所以实体类也比较多,本文就举一个对象 标品和培训服务 的例子,其他实体类类似
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("标品信息")
@HeadRowHeight(value = 33)
@ContentRowHeight(value = 30)
@ColumnWidth(value = 20)
@HeadStyle(fillBackgroundColor = 64)
@HeadFontStyle(bold = BooleanEnum.TRUE, fontHeightInPoints = 10, fontName = "微软雅黑")
@ContentFontStyle(fontHeightInPoints = 10, fontName = "微软雅黑")
@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER, borderTop = BorderStyleEnum.THIN, borderLeft = BorderStyleEnum.THIN, borderRight = BorderStyleEnum.THIN, borderBottom = BorderStyleEnum.THIN)
@ExcelIgnoreUnannotated
public class StandardDetailExcelVO {

    @ExcelProperty(value = "产品名称",index = 0)
    private String productName;

    @ExcelProperty(value = "类型", converter = ProductTypeConvert.class, index = 1)
    private Byte type;

    @ExcelProperty(value = "产品单价", index = 2)
    private String  productPriceDes;

    @ExcelProperty(value = "产品数量",index = 3)
    private String productNumDes;

    @ExcelProperty(value = "产品原总价(元)",converter = MoneyConvert.class,index = 4)
    @NumberFormat("#0.00")
    private Long oldTotalPrice;

    @ExcelProperty(value = "产品折后总价(元)",converter = MoneyConvert.class,index = 5)
    @NumberFormat("#0.00")
    private Long currentTotalPrice;

    @ExcelProperty(value = "税率", converter = TaxRateConvert.class, index = 6)
    private Double taxRate;

    @ExcelProperty(value = "产品功能清单",index = 7)
    @ContentFontStyle(fontHeightInPoints = 10, fontName = "微软雅黑",color = 12)
    private WriteCellData<String> productListUrlHyperlink;

    @ExcelProperty(value = "备注",index = 8)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER, wrapped = BooleanEnum.TRUE, borderTop = BorderStyleEnum.THIN, borderLeft = BorderStyleEnum.THIN, borderRight = BorderStyleEnum.THIN, borderBottom = BorderStyleEnum.THIN)
    private String remark;

    /**
     * 产品功能说明
     */
    private String productListUrl;

}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("培训服务")
@HeadRowHeight(value = 33)
@ContentRowHeight(value = 30)
@ColumnWidth(value = 20)
@HeadStyle(fillBackgroundColor = 27)
@HeadFontStyle(bold = BooleanEnum.FALSE, fontHeightInPoints = 10, fontName = "微软雅黑")
@ContentFontStyle(fontHeightInPoints = 10, fontName = "微软雅黑")
@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER, borderTop = BorderStyleEnum.THIN, borderLeft = BorderStyleEnum.THIN, borderRight = BorderStyleEnum.THIN, borderBottom = BorderStyleEnum.THIN)
public class TrainModuleExcelVO {

    /**
     * 培训类型
     */
    @ExcelProperty(value = {"培训服务","类型"},index = 0)
    private String type;

    @ExcelProperty(value = {"培训服务","类型"},index = 1)
    private String hide1;

    /**
     * 培训次数
     */
    @ExcelProperty(value = {"培训服务","培训次数"},index = 2)
    private Double times;

    @ExcelProperty(value = {"培训服务","培训次数"},index = 3)
    private String hide2;

    /**
     * 费用
     */
    @ExcelProperty(value = {"培训服务","培训单次费用(元/次)"},converter = MoneyConvert.class, index = 4)
    @NumberFormat("#0.00")
    private Long cost;

    /**
     * 培训服务费用
     */
    @JsonSerialize(using = MoneySerializer.class)
    @ExcelProperty(value = {"培训服务","培训总费用(元)"},converter = MoneyConvert.class, index = 5)
    @NumberFormat("#0.00")
    private Long totalPrice;

    @ExcelProperty(value = {"培训服务", "税率"}, converter = TaxRateConvert.class, index = 6)
    private Double taxRate;

    /**
     * 备注
     */
    @ExcelProperty(value = {"培训服务","备注"},index = 7)
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.LEFT, wrapped = BooleanEnum.TRUE, borderTop = BorderStyleEnum.THIN, borderLeft = BorderStyleEnum.THIN, borderRight = BorderStyleEnum.THIN, borderBottom = BorderStyleEnum.THIN)
    private String remark;

    @ExcelProperty(value = {"培训服务","备注"},index = 8)
    private String remark1;
}
2.2小计代码快

    /**
     * 写入小计
     *
     * @param excelWriter
     * @param writeSheet
     * @param baseVo
     * @param tableNo
     */
    private void writeSubtotal(ExcelWriter excelWriter, WriteSheet writeSheet, CollectBaseVo baseVo, Integer lastCol, Integer tableNo) {
        writeSubtotal(excelWriter, writeSheet, baseVo.getTaxPrice(), baseVo.getTaxUpperPrice(), baseVo.getNotTaxTotalPrice(), baseVo.getNotTaxTotalUpperPrice(), lastCol, tableNo);
    }

    /**
     * 写入小计
     *
     * @param excelWriter
     * @param writeSheet
     * @param taxPrice              含税价
     * @param taxUpperPrice         含税价大写
     * @param notTaxTotalPrice      不含税价
     * @param notTaxTotalUpperPrice 不含税价大写
     * @param tableNo
     */
    private void writeSubtotal(ExcelWriter excelWriter, WriteSheet writeSheet, Long taxPrice, String taxUpperPrice, Long notTaxTotalPrice, String notTaxTotalUpperPrice, Integer lastCol, Integer tableNo) {
        String taxPriceStr = String.format("%.2f",new BigDecimal(taxPrice).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        String notTaxTotalPriceStr = String.format("%.2f",new BigDecimal(notTaxTotalPrice).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        //不含税价
        SubtotalExcelVO notTaxTotal = SubtotalExcelVO.builder()
                .name("小计:")
                .priceType("不含税价")
                .priceStr("¥"+notTaxTotalPriceStr)
                .upperPriceStr(notTaxTotalUpperPrice)
                .build();
        //含税价
        SubtotalExcelVO taxTotal = SubtotalExcelVO.builder()
                .name("小计")
                .priceType("含税价")
                .priceStr("¥"+taxPriceStr)
                .upperPriceStr(taxUpperPrice)
                .build();
        TableMergeProperty tableMergeProperty = new TableMergeProperty(0, 1, 0, lastCol);
        WriteTable totalTable = EasyExcel.writerTable()
                .needHead(Boolean.FALSE)
                .head(SubtotalExcelVO.class)
                .tableNo(tableNo)
                .registerWriteHandler(new SubtotalMergeStrategy(Arrays.asList(tableMergeProperty)))
                .registerWriteHandler(new ColumnMergeStrategy(7, 8))
                .registerWriteHandler(new SubtotalCellStyleStrategy())
                .build();
        excelWriter.write(Arrays.asList(notTaxTotal, taxTotal), writeSheet, totalTable);
    }
2.3写入总合计

private void writeSummaryTotal(ExcelWriter excelWriter, WriteSheet writeSheet, CollectInfoVo collectInfoVo, BigDecimal summaryPrice, String upperSummaryPrice, Integer tableNo) {
        BigDecimal totalNotTaxPrice = collectInfoVo.getNotTaxTotalPrice() != null ? new BigDecimal(collectInfoVo.getNotTaxTotalPrice()) : new BigDecimal("0");
        String notTaxPrice = String.format("%.2f",totalNotTaxPrice.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        //不含税价
        SummaryExcelVO notTaxSummary = SummaryExcelVO.builder()
                .priceDetail("报价单描述:" + StringUtils.trimToEmpty(collectInfoVo.getPriceDetail()))
                .type("总合计:")
                .priceType("不含税价")
                .totalPriceStr("¥"+notTaxPrice)
                .upperTotalPriceStr(collectInfoVo.getNotTaxTotalUpperPrice())
                .build();
        //含税价
        String priceStr = String.format("%.2f",summaryPrice.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        SummaryExcelVO taxSummary = SummaryExcelVO.builder()
                .priceDetail("报价单描述:" + StringUtils.trimToEmpty(collectInfoVo.getPriceDetail()))
                .type("总合计:")
                .priceType("含税价")
                .totalPriceStr("¥"+priceStr)
                .upperTotalPriceStr(upperSummaryPrice)
                .build();

        TableMergeProperty priceDetailMergeProperty = new TableMergeProperty(0, 1, 0, 3);
        TableMergeProperty typeMergeProperty = new TableMergeProperty(0, 1, 4, 4);
        List<TableMergeProperty> tableMergeProperties = Arrays.asList(priceDetailMergeProperty, typeMergeProperty);
        WriteTable totalTable = EasyExcel.writerTable()
                .needHead(Boolean.FALSE)
                .head(SummaryExcelVO.class)
                .tableNo(tableNo)
                .registerWriteHandler(new SubtotalCellStyleStrategy())
                .registerWriteHandler(new ColumnMergeStrategy(7, 8))
                .registerWriteHandler(new SubtotalMergeStrategy(tableMergeProperties))
                .build();
        excelWriter.write(Arrays.asList(notTaxSummary, taxSummary), writeSheet, totalTable);
    }
3,导出标品的sheet


    /**
     * 导出标品内容
     *
     * @param standardInfo
     * @param excelWriter
     */
    private void writeStandardDetail(StandardInfoVO standardInfo, ExcelWriter excelWriter) {
        if (standardInfo != null && CollectionUtils.isNotEmpty(standardInfo.getStandards())) {
            WriteSheet writeSheet = EasyExcel.writerSheet("标品").build();
            int tableNo = 0;
            if (!standardInfo.getIsExport()) {
                //有效期
                String priceDataInfo = getPriceDataInfo(standardInfo.getPriceData(), standardInfo.getExpirationDay());
                ContactInfoExcelVO priceDataInfoVO = ContactInfoExcelVO.builder()
                        .contactInfo(priceDataInfo)
                        .build();
                WriteTable priceDataInfoTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.FALSE).registerWriteHandler(new ColumnMergeStrategy(0, 6)).head(ContactInfoExcelVO.class).build();
                excelWriter.write(Arrays.asList(priceDataInfoVO), writeSheet, priceDataInfoTable);
            }
            List<StandardDetailExcelVO> standardDetailExcelVOS = standardInfo.getStandards().stream()
                    .map(standInfoConverter::toDetailExcel).collect(Collectors.toList());
            standardDetailExcelVOS.stream().forEach(standardDetailExcelVO -> {
                // 设置功能清单
                if (StringUtils.isNotBlank(standardDetailExcelVO.getProductListUrl())) {
                    WriteCellData<String> hyperlink = new WriteCellData<>("点击查看");
                    standardDetailExcelVO.setProductListUrlHyperlink(hyperlink);
                    HyperlinkData hyperlinkData = new HyperlinkData();
                    hyperlink.setHyperlinkData(hyperlinkData);
                    hyperlinkData.setAddress(standardDetailExcelVO.getProductListUrl());
                    hyperlinkData.setHyperlinkType(HyperlinkData.HyperlinkType.URL);
                }
            });
            WriteTable writeTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.TRUE).head(StandardDetailExcelVO.class).build();
            excelWriter.write(standardDetailExcelVOS, writeSheet, writeTable);
            //    总计
            //StandardDetailExcelVO total = new StandardDetailExcelVO();
            //total.setProductName("总计:");
            //total.setCurrentTotalPrice(standardInfo.getStandardTotalPrice());
            //writeTotal(excelWriter, writeSheet, total, tableNo++, 0, 3);
            //writeStandardSubtotal(excelWriter,writeSheet,standardInfo.getStandardTotalPrice(),standardInfo.getStandardTotalUpperPrice(),tableNo++);

            writeSubtotal(excelWriter, writeSheet, standardInfo.getTaxPrice(), standardInfo.getTaxUpperPrice(), standardInfo.getNotTaxTotalPrice(), standardInfo.getNotTaxTotalUpperPrice(), 4, tableNo++);


        }

    }
4导出定开的内容

@SneakyThrows
    private void writeDynamicOpeningInfos(OpeningInfoVO openingVO, CollectBaseVo baseVo, List<String> columnNames, List<String> developmentColumnNames, ExcelWriter excelWriter) {
        List<ModuleInfoVo> moduleInfos = openingVO.getModuleInfos();
        if (CollectionUtils.isNotEmpty(moduleInfos)) {
            //查询动态表头格式
            PriceOpenContentExcel priceOpenContentExcel = iPriceOpenContentExcelService.selectByPriceOpenId(openingVO.getId());
            List<OpenDetailDevelopmentResult> openDetailDevelopmentResults = JSON.parseArray(priceOpenContentExcel.getDynamicHead(), OpenDetailDevelopmentResult.class);
            //根据动态表头动态生成class
            Map<String, String> params = new HashMap<>();
            Class<? extends OpeningDetailExcelVo> openingDetailExcelVoClazz = assembleTemplateClass(openDetailDevelopmentResults, params);

            List<OpeningDetailExcelVo> openingDetailExcelVos = moduleInfos.stream().map(openingConverter::toDetailExcel).collect(Collectors.toList());
            List<? extends OpeningDetailExcelVo> detailExcelVos = BeanUtil.copyToList(openingDetailExcelVos, openingDetailExcelVoClazz);
            assembleDynamicFieldsAndCalculateTotal(detailExcelVos, openingDetailExcelVoClazz);
            //获取排除的列
            List<Field> excludeColumnField = getExcludeColumnFields(openingDetailExcelVoClazz, columnNames);
            //获取合并单元格并根据排除列重新计算合并单元格坐标
            ExcelMergeStrategy excelMergeStrategy = calculateMergeProperty(priceOpenContentExcel, excludeColumnField);
            List<String> excludeColumnFieldNames = excludeColumnField.stream().map(Field::getName).collect(Collectors.toList());
            WriteSheet writeSheet = EasyExcel.writerSheet(openingVO.getOpeningName()).registerWriteHandler(new HeadWriteHandler(params)).excludeColumnFieldNames(excludeColumnFieldNames).head(openingDetailExcelVoClazz).build();
            int tableNo = 0;
            WriteTable writeTable = EasyExcel.writerTable().tableNo(tableNo++).needHead(Boolean.FALSE).registerWriteHandler(excelMergeStrategy).build();
            excelWriter.write(detailExcelVos, writeSheet, writeTable);
            //总列数-研发项列数-备注一列
            //Integer lastCol = CollectionUtils.size(columnNames) - CollectionUtils.size(developmentColumnNames) - (excludeColumnFieldNames.contains("remark")?0:1) - 1;
            if (CollectionUtils.size(columnNames) - 4 >= 0) {
                //小计
                writeDynamicHeadSubtotal(excelWriter, writeSheet, baseVo, CollectionUtils.size(columnNames), CollectionUtils.size(columnNames) - 4, tableNo++);
            }
        }
    }

4.1导出定开的小计

private void writeDynamicHeadSubtotal(ExcelWriter excelWriter, WriteSheet writeSheet, CollectBaseVo baseVo, Integer headSize, Integer lastCol, Integer tableNo) {

        Long taxPrice = baseVo.getTaxPrice();
        String taxPriceStr = String.format("%.2f",new BigDecimal(taxPrice).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        Long notTaxTotalPrice = baseVo.getNotTaxTotalPrice();
        String notTaxTotalPriceStr = String.format("%.2f",new BigDecimal(notTaxTotalPrice).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        List<List<String>> headList = ListUtils.newArrayList();
        List<String> head = ListUtils.newArrayList();
        for (int i = 0; i <= lastCol; i++) {
            head.add("小计:");
        }
        head.add("金额类型");
        head.add("金额");
        head.add("大写金额");
        headList.add(head);
        List<List<String>> dataList = ListUtils.newArrayList();
        List<String> notTaxTotal = ListUtils.newArrayList();
        for (int i = 0; i <= lastCol; i++) {
            notTaxTotal.add("小计:");
        }
        notTaxTotal.add("不含税价");
        notTaxTotal.add("¥"+notTaxTotalPriceStr);
        notTaxTotal.add(baseVo.getNotTaxTotalUpperPrice());
        dataList.add(notTaxTotal);
        List<String> taxTotal = ListUtils.newArrayList();
        for (int i = 0; i <= lastCol; i++) {
            taxTotal.add("小计:");
        }
        taxTotal.add("含税价");
        taxTotal.add("¥"+taxPriceStr);
        taxTotal.add(baseVo.getTaxUpperPrice());
        dataList.add(taxTotal);
        TableMergeProperty tableMergeProperty = new TableMergeProperty(0, 1, 0, lastCol);

        SubtotalRepeatMergeStrategy subtotalRepeatMergeStrategy = new SubtotalRepeatMergeStrategy(Arrays.asList(tableMergeProperty));
        WriteTable totalTable = EasyExcel.writerTable()
                .needHead(Boolean.FALSE)
                .head(headList)
                .tableNo(tableNo)
                .registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 33, (short) 30))
                .registerWriteHandler(subtotalRepeatMergeStrategy)
                .registerWriteHandler(new SubtotalCellStyleStrategy())
                .build();
        excelWriter.write(dataList, writeSheet, totalTable);
        subtotalRepeatMergeStrategy.setFirstRow();
    }



至此,导出内容完毕



 
                    

到了这里,关于java 实现 excel 自定义样式和字段导出的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 前端vue导出excel(标题加粗+表头自定义样式+表格边框+单元格自定义样式)

    接近过年,被一大堆excel报表烦死的我,遇到要求前端导出excel的后端,差点猝死的我拼命学习中,整理出这篇文章,希望看到这篇文章的你有所收获,也希望能收到大佬们的指点 之前用c#,.net弄过导出word,excel,可以点击查看.NET使用Aspose控件生成Word(可构建自定义表格)、

    2024年04月15日
    浏览(56)
  • 【Java】使用POI按模板样式导出Excel

    根据模板样式进行excel导出。 首先,当然是要有一个excel模板,excel的样式用wps等进行设置。 然后就是代码的实现了,先引入POI的依赖: 然后就是实现方法里的代码,首先定义响应信息: 然后将excel模板转为输入流,这一步的实现方法有很多,具体选择因人而异,我这里就举

    2024年02月14日
    浏览(46)
  • 使用EasyPoi实现Excel的按模板样式导出

    1690342020350导出测试.xlsx 如下 #fe 使用#fe命令可以实现集合数据的横向拓展,比如模板代码是 导出的excel里面就会显示会自当前列,向右拓展,效果可参见下面的导出文件截图 v_fe 使用v_fe命令可以实现不固定列的横向遍历,比如模板代码是 分数 ID {{#fe:maths t.score t.id}} 这种情况

    2024年02月15日
    浏览(47)
  • 纯前端 —— 200行JS代码、实现导出Excel、支持DIY样式,纵横合并

    前期回顾 Vue3 + TS + Element-Plus 封装Tree组件 《亲测可用》_vue3+ts 组件封装-CSDN博客 https://blog.csdn.net/m0_57904695/article/details/131664157?spm=1001.2014.3001.5501 目录 具体思路: 1. 准备HTML结构 2. 定义CSS样式 3. 初始化表格数据 4. 创建表格函数createTable 5. 将表格添加到页面中 6. 导出表格为E

    2024年02月02日
    浏览(37)
  • java中用SXSSFWorkbook把多个字段的list数据和单个实体dto导出到excel如何导出到多个sheet页详细实例?

    要使用SXSSFWorkbook将多个字段的List数据和单个实体DTO导出到多个Sheet页,你可以按照以下步骤进行操作: 创建一个SXSSFWorkbook对象作为工作簿。 针对每个字段的List数据,创建一个新的Sheet页,并将数据写入该Sheet页。 创建一个新的Sheet页,用于单个实体DTO的数据。 将单个实体

    2024年02月11日
    浏览(44)
  • Java 操作 Excel:生成数据、设置单元格样式、设置数据有效性(hutool)

    该篇文章,主要通过 Java 代码对 Excel 文件的常用操作,包括:生成表格、修改单元格样式、设置数据有效性。 该篇文章,在官网文献下增加个人的看法和理解,如文中有出现不符、错误或需要补充的地方,欢迎指正,非常感谢。 该篇文章操作 Excel 使用了 hutool 的工具包以及

    2024年02月04日
    浏览(37)
  • Java使用poi导出excel针对不同数据列配置设置不同单元格格式(适用于通用导出excel数据)

    公司大部分业务都是查询相关的业务, 所以建了一个项目专门做数据查询, 数据中转等抽象通用的业务, 有一天给我安排了一个功能, 做excel导出, 配置好查询sql和表头字段映射后即可导出excel, 无需修改代码 后来因为导出数据要求保留几位小数或者转换成百分比等设置单元格格

    2024年02月07日
    浏览(52)
  • <Java导出Excel> 1.0 Java实现Excel动态模板导出

    思路: 1,先创建动态模板(必须要在数据库建一张表,可随时修改模板) 例如: 建表语句: 模板中的字段脚本: 2,编写一个查询接口:返回一个List map 注意:order by id 根据表中字段:id排序的作用是控制导出的EXCEL表中字段列的顺序; mapper.xml层: mapper接口层: serviceIm

    2024年02月12日
    浏览(47)
  • java-EasyExcel导出excel设置单元格为文本格式(含代码)

    java-EasyExcel导出excel设置单元格为文本格式(含代码) 在使用EasyExcel导出excel模板时。我们会发现导出的日期和大长度数字都会自动更换格式,不是文本格式。并且在空白单元格输入日期也是格式有问题的,如下所示,可以看到当输入相同的日期时,格式会变成自适应,不是文

    2023年04月15日
    浏览(45)
  • 若依@Excel注解自动获取导出字段,字典解析

    若依系统中实体类导出字段使用了 @Execl 如不是若依系统 最后附有excel接口 普通导出: @Excel (name = \\\"单位\\\") private String unit; 带字典解析导出: @Excel (name = \\\"状态\\\", dictType = \\\"sys_true_false\\\") private Integer attributeCategory; 系统后台字典配置: 新增的字典也会存在redis缓存中(直接查询缓存

    2024年02月11日
    浏览(73)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包