关于动态生成html中的table表格样式模版,Java。利用Document和Element类。

类似于生成此动态,需要根据业务去合并不同数量的单元格的table表格。

思路便是:先创建一个模板单元格,然后通过其属性去动态更改table中的元素标签。

 利用模版:

<table style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<td style="width: 23.2763%;">&nbsp;</td>
<td style="width: 23.2763%;">&nbsp;</td>
<td style="width: 23.2763%;">&nbsp;</td>
<td style="width: 23.2763%;">&nbsp;</td>
</tr>
</tbody>
</table>

 按照实体类中的一个集合属性去判断合并多少单元格,遍历集合中的数据获得需合并单元格多少单元格的数据

实体类:

@Data
public class ICBmEvaluationDocumentDTO {

    //标题
    private String a;

   //细则集合
    private List<ICBmEvaluationDetailDTO> icBmEvaluationDetailDTOS;

}

 List<ICBmEvaluationDetailDTO>中有多少元素,就合并多少单元格。一个标题a为一个整的单元格。

@Data
public class ICBmEvaluationDetailDTO {
    //编号
    private String number;

    //评审指标
    private String reviewIndicators;

    //等级要求
    private String grade;

    //评审内容
    private String reviewContent;
}

工具类: 


import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ICEdTemplateUtils {

    private static Logger logger = LoggerFactory.getLogger(ICEdTemplateUtils.class);

    /**
     * 填充表格
     * @param <T>
     * @param table         表格对象
     * @param icBmEvaluationDocumentDTOS  数据
     * @param consumer      具体填充方式
     * @param placeHolder   定位数据行tr的占位符
     * @param removeLast
     * @return
     */
    public static <T> Element fillTable(Element table, List<ICBmEvaluationDocumentDTO> icBmEvaluationDocumentDTOS, BiConsumer<Element, ICBmEvaluationDetailDTO> consumer, String placeHolder, boolean removeLast){
        if (table == null){
            return null;
        }
        Element td = getPlaceholderParentFilterByTag(table, placeHolder, "tr");
        if (td == null){
            throw new CustomException("找不到表格中的行元素");
        }
        Element emptyTd = td.clone();
        Element nextRow;
        for (ICBmEvaluationDocumentDTO item : icBmEvaluationDocumentDTOS) {
            List<ICBmEvaluationDetailDTO> child = item.getIcBmEvaluationDetailDTOS();
            Integer size = child.size();
            if (size == 1) {
                //将数据拆分出来
                ICBmEvaluationDetailDTO icBmEvaluationDetailDTO = child.get(0);
                icBmEvaluationDetailDTO.setReviewContent(item.getReviewContent());

                consumer.accept(td, icBmEvaluationDetailDTO);
                nextRow = emptyTd.clone();
                td.after(nextRow);
                td = nextRow;
            } else {
                //获取第一个tr列的对象
                Element esTr = td.select("tr").first();
                //获取第一个tr列对象中的height
                String heightTr = esTr.attr("style");
                //获取字符串中的所有数字
                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(heightTr);
                int s = Integer.parseInt(m.replaceAll("").trim());
                //将height根据合并单元格数量扩大
                Integer heightMax = s * size;

                //获取第一个td列的对象
                Element esTd = td.select("td").first();
                //修改style
                String heightTd = esTd.attr("style");
                String[] he = heightTd.split(";");
                String widthS = null;
                for (int i = 0; i < he.length; i++) {
                    if (he[i].contains("width")) {
                        widthS = he[i];
                    }
                }

                //style的值
                String style = widthS + ";" + "height: " + heightMax + "px;";

                //修改其中height的值
                for (int i = 0; i < size; i++) {
                    //
                    if (i == 0) {
                        ICBmEvaluationDetailDTO child1 = child.get(i);
                        //修改style属性的值
                        td.select("td").first().attr("style", style);
                        //新增rowspan的值
                        td.select("td").first().attr("rowspan", String.valueOf(size));
                        child1.setReviewContent(item.getReviewContent());
                        consumer.accept(td, child1);
                        nextRow = emptyTd.clone();
                        td.after(nextRow);
                        td = nextRow;
                    } else {
                        ICBmEvaluationDetailDTO child2 = child.get(i);
                        //删除一个td列
                        td.select("td").first().remove();
                        consumer.accept(td, child2);
                        nextRow = emptyTd.clone();
                        td.after(nextRow);
                        td = nextRow;
                    }
                }

            }
        }
        if (removeLast){
            td.remove();
        }
        return td;
    }

    /**
     *  医疗机构情况 -- 医疗情况
     * @param condition
     * @param icEdCondition
     * @param consumer
     * @param placeHolder
     * @param removeLast
     * @param <T>
     * @return
     */
    public static <T> Element fillCondition(Element condition, ICEdCondition icEdCondition, BiConsumer<Element, ICEdCondition> consumer, String placeHolder, boolean removeLast){
        if(condition == null){
            return null;
        }

        Element trCondition = getPlaceholderParentFilterByTag(condition, placeHolder, "tr");
        if (trCondition == null){
            throw new CustomException("找不到表格中的行元素!");
        }
        consumer.accept(trCondition, icEdCondition);
        return trCondition;
    }

    /**
     * 获取指定标签的占位符的父级元素
     * @param element       html对象
     * @param placeholder   占位符
     * @param tag           html标签
     * @return
     */
    public static Element getPlaceholderParentFilterByTag(Element element, String placeholder, String tag){
        Element index = element.getElementsContainingOwnText(placeholder).first();
        while (true){
            if (index == null){
                logger.warn("找不到占位符" + placeholder);
                return null;
            }
            if (index.is(tag)){
                return index;
            }
            index = index.parent();
            if (index.is("body")){
                logger.warn("找不到占位符" + placeholder);
                return null;
            }
        }
    }

    /**
     * 填充占位符(填充所有匹配到的)
     * @param element       html对象
     * @param placeholder   占位符
     * @param value         填充值
     */
    public static void replace(Element element, String placeholder, String value){
        if (placeholder == null){
            return;
        }
        if (value == null){
            value = "";
        }
        for (Element target : element.getElementsContainingOwnText(placeholder)) {
            target.removeAttr("contenteditable");
            target.parent().removeClass("mymention");
            String html = target.html();
            target.html(html.replace(placeholder, value));
        }
    }


}

 实现类:




/**
 * 文档模板编写实现类
 */


public class DocumentOperation  {

    /**
     * 填充医疗机构情况-医疗情况
     * @param templateDetailContent
     * @param icBmEvaluationDocumentDTOS
     * @return
     * @throws Exception
     */
    @Override
    protected String fillTemplate2(String templateDetailContent, List<ICBmEvaluationDocumentDTO> icBmEvaluationDocumentDTOS) throws Exception {
        Document document = Jsoup.parse(templateDetailContent);
        Element body = document.body();
        //填充表格模板
        fillTable(body,icBmEvaluationDocumentDTOS);
        return body.html();
    }

    /**
     * 填充表格模板
     * @param body
     * @param icBmEvaluationDocumentDTOS
     */
    private void fillTable(Element body, List<ICBmEvaluationDocumentDTO> icBmEvaluationDocumentDTOS){
        ICEdTemplateUtils.fillTable(
                getPlaceholderParentFilterByTag(body, "{评审内容}","table"),
                icBmEvaluationDocumentDTOS,
                (row, lysjjlb) -> {
                    replace(row, "{评审内容}", lysjjlb.getReviewContent());
                    replace(row, "{编号}", lysjjlb.getNumber());
                    replace(row, "{评审指标}", lysjjlb.getReviewIndicators());
                    replace(row, "{等级要求}", lysjjlb.getGrade());
                        }, "{评审内容}", true);

    }
    
}

用法:

        //填充评审内容表格
        List<ICBmEvaluationDocumentDTO> list = new ArrayList<>();
        //表格
        String table = "<table style=\"border-collapse: collapse; width: 100%; height: 30px;\" border=\"1\"><tbody><tr style=\"height: 30px;\"><td style=\"width: 23.2763%; height: 30px;\">{评审内容}</td><td style=\"width: 23.2763%; height: 30px;\">{编号}</td><td style=\"width: 23.2763%; height: 30px;\">{评审指标}</td><td style=\"width: 23.2763%; height: 30px;\">{等级要求}</td></tr></tbody></table>";
        
        //填充内容生成表单
        String matter = projectTextOperation.fillTemplate2(table, list);

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要在Vue使用xlsx和xlsx-style插件将Element UITable组件的表格导出并下载,可以按照以下步骤进行操作: 1. 安装xlsx和xlsx-style插件。打开终端并导航到你的Vue项目目录,运行以下命令: ``` npm install xlsx xlsx-style ``` 2. 在需要导出表格的组件,使用import语句导入xlsx和xlsx-style模块: ```javascript import XLSX from 'xlsx'; import 'xlsx-style/dist/xlsx.core.min.js'; // 导入xlsx-style模块 ``` 3. 在需要导出表格的组件,创建一个方法来处理导出逻辑。例如,创建一个名为`exportTable`的方法: ```javascript exportTable() { // 获取要导出的表格数据 const tableData = this.$refs.table.$el; // 创建一个空的工作簿对象 const wb = XLSX.utils.book_new(); // 创建一个工作表对象 const ws = XLSX.utils.table_to_sheet(tableData); // 将工作表添加到工作簿 XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); // 将样式应用到工作表的单元格(如果需要) // 可以使用xlsx-style插件提供的API来设置样式 // 将工作簿对象转换成二进制数据 const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' }); // 创建一个Blob对象 const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' }); // 创建一个下载链接并模拟点击下载 const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'table.xlsx'; link.click(); // 释放URL对象 window.URL.revokeObjectURL(url); } ``` 4. 在模板,将导出按钮绑定到`exportTable`方法: ```html <template> <div> <el-button type="primary" @click="exportTable">导出表格</el-button> <el-table ref="table" :data="tableData"> <!-- 表格内容 --> </el-table> </div> </template> ``` 在这个示例,我们使用`refs`属性获取了Table组件的DOM元素,并将其作为参数传递给`table_to_sheet`方法来创建工作表对象。然后,我们将工作表对象添加到工作簿,并使用`write`方法将工作簿对象转换成二进制数据。最后,我们创建了一个Blob对象,并使用创建的下载链接来模拟点击下载。 请注意,上述示例的`tableData`和`s2ab`函数需要根据你的实际情况进行调整。`tableData`应该是你要导出的表格数据,而`s2ab`函数是一个将字符串转换成ArrayBuffer的辅助函数(可在下面找到实现)。 ```javascript function s2ab(s) { const buf = new ArrayBuffer(s.length); const view = new Uint8Array(buf); for (let i = 0; i < s.length; i++) { view[i] = s.charCodeAt(i) & 0xFF; } return buf; } ``` 这样,当你点击“导出表格”按钮时,表格数据将以Excel文件的形式下载到本地。 希望这可以帮助到你!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值