poi-tl 列宽自适应

文章介绍了如何在Java项目中使用Poi-tl库创建Word文档,并解决表格列宽自适应的问题。通过修改TableTools.setWidth方法,实现表格宽度的动态设置,使得表格宽度可以自动适应内容。
摘要由CSDN通过智能技术生成

官网链接
Poi-tl Documentation

引入依赖

maven

<dependency>
  <groupId>com.deepoove</groupId>
  <artifactId>poi-tl</artifactId>
  <version>1.12.2</version>
</dependency>

Gradle

implementation 'com.deepoove:poi-tl:1.12.2'

基础案例一

package com.deepoove.poi.examples;


import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.CellStyle;
import com.deepoove.poi.data.style.ParagraphStyle;
import com.deepoove.poi.data.style.RowStyle;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.deepoove.poi.xwpf.NumFormat;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @program: base-utils.
 * @description: TODO.
 * @author: 111111.
 * @created: 2024/04/09 08:34.
 */
public class WordTest02 {
    public static void main(String[] args) throws IOException {
        NiceXWPFDocument document = new NiceXWPFDocument();
        Documents.DocumentBuilder builder = Documents.of();
        BigInteger numId = document.addNewMultiLevelNumberingId(NumberingFormat.DECIMAL, new NumberingFormat(NumFormat.DECIMAL, "%1.%2."));
        // 1.
        ParagraphRenderData paraOfNumbering0 = Paragraphs.of().addText(
            Texts.of("I consider myself the luckiest man").create())
            .paraStyle(ParagraphStyle.builder().withNumId(numId.longValue()).withLvl(0).build()).create();
        // 1. 1.
        ParagraphRenderData paraOfNumbering00 = Paragraphs.of().addText("I consider myself the luckiest man")
            .paraStyle(ParagraphStyle.builder().withNumId(numId.longValue()).withLvl(1).build()).create();
        // 1. 1.
        ParagraphRenderData paraOfNumbering01 = Paragraphs.of().addText("I consider myself the luckiest man")
            .paraStyle(ParagraphStyle.builder().withNumId(numId.longValue()).withLvl(1).build()).create();
        // 2.
        ParagraphRenderData paraOfNumbering1 = Paragraphs.of().addText("I consider myself the luckiest man")
            .paraStyle(ParagraphStyle.builder().withNumId(numId.longValue()).withLvl(0).build()).create();
        builder.addParagraph(paraOfNumbering0)
            .addParagraph(Paragraphs.of()
                .addText("测试哇").create())
            .addParagraph(paraOfNumbering00).addParagraph(paraOfNumbering01).addParagraph(paraOfNumbering1);


        builder.addParagraph(Paragraphs.of("标题2").create());
        RowRenderData row0 = Rows.of("列0", "列1", "列2").center().create();
        RowRenderData row1 = Rows.create("没有数据", null, "郑州市航空港区金陵大道浮清河路口");
        RowStyle rowStyle = new RowStyle();
        CellStyle cellStyle = new CellStyle();
        cellStyle.setDefaultParagraphStyle(ParagraphStyle.builder()
            .withAlign(ParagraphAlignment.CENTER)
            .withIndentFirstLineChars(0)
            .build());
        rowStyle.setDefaultCellStyle(cellStyle);
        row1.setRowStyle(rowStyle);
        builder.addTable(Tables.create(row0, row1)).create();
        TableRenderData renderData = Tables.of(row0, row1).center().create();
        builder.addParagraph(new ParagraphRenderData());
        builder.addTable(renderData);
        DocumentRenderData documentRenderData = builder.create();
        XWPFTemplate template = XWPFTemplate.create(document,documentRenderData);
        template.writeAndClose(Files.newOutputStream(Paths.get("c:/tmp/builder-02.docx")));
    }
}

问题一 列宽自适应

image.png

  • 上述生成的word文档中表格列宽无法使用自适应 对 第一个表格进行修改 使用 ofAutoWidth();
Tables.TableBuilder tableBuilder = Tables.ofAutoWidth();
        tableBuilder.addRow(row0);
        tableBuilder.addRow(row1);
        builder.addTable(tableBuilder.create()).create();
/**
 * 会发现如下问题 虽然确实是自适应了,但是宽度变得不是我们想要的了 这个宽度在哪里设置的呢
*/

image.png

经查阅源码 setWidth 方法中 TableWidthType.PCT 是多列均分表格宽度
而自适应 TableWidthType.AUTO 中未做宽度设定 那宽度从哪里来的呢?
继续查阅 点 table.setWidth(width); 方法进去,一直点到下面第三段代码中会发现,auto初始化为0 ctWidth.setW(BigInteger.ZERO)

public static TableBuilder of(RowRenderData... row) {
    TableBuilder inst = ofPercentWidth("100%");
    if (null != row) {
        Arrays.stream(row).forEach(inst::addRow);
    }
    return inst;
}
... 
public static void setWidth(XWPFTable table, String width, int[] colWidths) {
        ensureTblW(table);
        table.setWidth(width);
        if (null == colWidths) {
            int columnSize = TableTools.obtainColumnSize(table);
            if (table.getWidthType() == TableWidthType.DXA) {
                colWidths = UnitUtils.average(Integer.valueOf(width), columnSize);
            } else if (table.getWidthType() == TableWidthType.PCT) {
                int sum = 0;
                colWidths = new int[columnSize];
                for (int i = 0; i < columnSize - 1; i++) {
                    colWidths[i] = 100 / columnSize;
                    sum += colWidths[i];
                }
                colWidths[columnSize - 1] = 100 - sum;
            } else if (table.getWidthType() == TableWidthType.AUTO) {
            }
        }
    }


... 
protected static void setWidthValue(String widthValue, CTTblWidth ctWidth) {
        if (!widthValue.matches(REGEX_WIDTH_VALUE)) {
            throw new RuntimeException("Table width value \"" + widthValue + "\" "
                    + "must match regular expression \"" + REGEX_WIDTH_VALUE + "\".");
        }
        if (widthValue.matches("auto")) {
            ctWidth.setType(STTblWidth.AUTO);
            ctWidth.setW(BigInteger.ZERO);
        } else if (widthValue.matches(REGEX_PERCENTAGE)) {
            setWidthPercentage(ctWidth, widthValue);
        } else {
            // Must be an integer
            ctWidth.setW(new BigInteger(widthValue));
            ctWidth.setType(STTblWidth.DXA);
        }
    }

问题一解决方案

// 在 setWIdth方法中 添加如下代码
else if (table.getWidthType() == TableWidthType.AUTO) {
  table.setWidth("100%");
}

在运行 会发现完全满足要求
image.png

/**
 * 但是写死会有点不优雅 所以继续做修改 在 Tables.java 中增加如下方法 
*/
// 这俩是 builder内的方法
public TableBuilder autoWidth(String autoWidth) {
    TableStyle style = getTableStyle();
    style.setWidth("auto,"+autoWidth);
    return this;
}

public TableBuilder autoWidth(Integer autoWidth) {
    return this.autoWidth(autoWidth+"%");
}

// 这个是Tables 的方法
public static TableRenderData createAutoWidth(RowRenderData... row) {
    return of(row).autoWidth().create();
}
/**
 * TableTools 中的 setWidth 方法 修改这个代码块
*/
public static void setWidth(XWPFTable table, String width, int[] colWidths) {
    ensureTblW(table);
    //table.setWidth(width); // TODO 这个设置会对宽度进行设定 ctWidth.setW(BigInteger.ZERO); 后续自己覆盖这个值即可
    // TODO 由于需要动态的传入值 在此对width 进行修改 可正常传入 xxx%  但auto模式的数据是由逗号隔开的 eg. auto,xxx%
    String percentage = "100%";
    if(width.startsWith("auto,")) {
        percentage = width.split(",")[1];
        width = "auto";
    }
    table.setWidth(width);
    if (null == colWidths) {
        int columnSize = TableTools.obtainColumnSize(table);
        if (table.getWidthType() == TableWidthType.DXA) {
            colWidths = UnitUtils.average(Integer.valueOf(width), columnSize);
        } else if (table.getWidthType() == TableWidthType.PCT) {
            int sum = 0;
            colWidths = new int[columnSize];
            for (int i = 0; i < columnSize - 1; i++) {
                colWidths[i] = 100 / columnSize;
                sum += colWidths[i];
            }
            colWidths[columnSize - 1] = 100 - sum;
        } else if (table.getWidthType() == TableWidthType.AUTO) {
            table.setWidth(StringUtils.isNotBlank(width) ? width.equals("auto") ? "100%" : percentage : "100%");
        }
    }
    // other codes....
}

调整案例代码

builder.addTable(Tables.createAutoWidth(row0, row1)).create();
TableRenderData renderData = Tables.of(row0, row1).center().create();

结果如下 同样满足自适应
image.png

  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
poi-tl是一种基于Apache POI和FreeMarker模板引擎的Java模板引擎,它可以帮助我们方便地生成各种格式的文档,包括Word、Excel和PowerPoint等。如果您想要替换Word文档中的图片,可以通过以下步骤实现: 1. 在Word文档中找到需要替换的图片,并记下它的编号或名称; 2. 在POI-TL模板中添加一个标签,用于指定图片的位置,例如:${picture}; 3. 在Java代码中使用POI-TL提供的API,通过标签名称找到对应的位置,并将新的图片插入到该位置。 以下是具体的Java代码实现示例: ```java // 创建POI-TL配置对象 Configuration config = new Configuration(); // 设置POI-TL使用的模板文件所在目录 config.setTemplateDir("templateDir"); // 设置POI-TL使用的模板文件名 config.setTemplateName("templateName.docx"); // 创建数据模型对象 Map<String, Object> data = new HashMap<>(); // 将需要替换的图片名称或编号放入数据模型中 data.put("picture", "newPicture.jpg"); // 创建POI-TL对象 DocxRenderData docx = new DocxRenderData(new File("templateName.docx"), data); // 将POI-TL对象写入新的Word文档中 XWPFTemplate template = XWPFTemplate.compile("output.docx", config).render(docx); template.write(new FileOutputStream("output.docx")); template.close(); ``` 在上面的代码中,我们首先创建了一个POI-TL配置对象,并设置了模板文件所在目录和模板文件名。然后创建了一个数据模型对象,并将需要替换的图片名称或编号放入该对象中。接着,我们创建了一个POI-TL对象,并将其写入新的Word文档中。 在模板文件中,我们使用了`${picture}`标签来指定图片的位置。在Java代码中,我们使用了POI-TL提供的API来找到该标签,并将新的图片插入到该位置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值