java 使用poi实现对word指定位置合并、增加、行列、指定位置增加标签、标签增加内容。

使用poi增加word行和列
先上一点简单的dome:复制指定行
注意、不管是表格数量、还是行列数量、都是从0计算。

<dependency>
  <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
public static void main(String[] args) throws IOException {
        XWPFDocument document  = new XWPFDocument(new FileInputStream("C:\\upload\\dome\\1.docx"));
        XWPFTable xwpfTable = document.getTables().get(0);//这里代表获取word里面第一个表格。
        //xwpfTable.createRow();增加列
        xwpfTable.addRow(xwpfTable.getRow(5),9);//代表复制第5行,复制到第9行
        xwpfTable.addRow(xwpfTable.getRow(6),10);
        xwpfTable.addRow(xwpfTable.getRow(7),11);
        xwpfTable.addRow(xwpfTable.getRow(8),12);

        String string  ="C:\\file\\12.docx";
        FileOutputStream out = new FileOutputStream(string);
        document.write(out);
        document.close();
        out.close();
    }

合并单元格dome

public static void main(String[] args) throws IOException {
        XWPFDocument document  = new XWPFDocument(new FileInputStream("C:\\file\\1.docx"));
        XWPFTable xwpfTable = document.getTables().get(0);
        //行合并参数:表格,列,开始行,结束行
        mergeCellsVertically(xwpfTable, 0, 5, 12);
        ///列合并参数:表格,行,开始列,结束列
        //mergeCellsHorizontal(table, 4, 0, 2);

        String string  ="C:\\file\\12.docx";
        FileOutputStream out = new FileOutputStream(string);
        document.write(out);
        document.close();
        out.close();
}
/**
     * word单元格行合并
     * @param table 表格
     * @param col 合并行所在列
     * @param fromRow 开始行
     * @param toRow 结束行
     */
    public static void mergeCellsVertically(XWPFTable table, int col, int startRow, int endRow) {
        for (int i = startRow; i <= endRow; i++) {
            XWPFTableCell cell = table.getRow(i).getCell(col);
            if (i == startRow) {
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

/**
     * word单元格列合并
     * @param table 表格
     * @param row 合并列所在行
     * @param startCell 开始列
     * @param endCell 结束列
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int startCell, int endCell) {
        for (int i = startCell; i <= endCell; i++) {
            XWPFTableCell cell = table.getRow(row).getCell(i);
            if (i == startCell) {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

循环增加标签、以便于后期插入数据dome

public static void main(String[] args) throws IOException {

        XWPFDocument document  = new XWPFDocument(new FileInputStream("C:\\file\\123.docx"));
        XWPFTable xwpfTable = document.getTables().get(0);
		//直接增加文字
        xwpfTable.getRow(0).getCell(1).setText("隐患"+w);
        //增加文字标签
        xwpfTable.getRow(0).getCell(3).setText("{{att}}");
        //增加插入图片标签 一定要加@
        xwpfTable.getRow(0).getCell(3).setText("{{@att1}}");
           
        String string  ="C:\\file\\12.docx";
        FileOutputStream out = new FileOutputStream(string);
        document.write(out);
        document.close();
        out.close();
    }

对指定标签增加数据与图片请添加图片描述

<dependency>
   <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.8.2</version>
</dependency>
public static void main(String[] args) throws IOException {
		Map<String,Object> map = new HashMap<>();
		try {
			//测试代码
			String destination = RestConfig.PATH+":\\upload\\dome\\jpgzgq\\12.jpg";

			File file=new File(destination);
			if(file.exists()){
				file.delete();
			}
			FileOutputStream downloadFile = new FileOutputStream(destination);
			downloadFile.write(b);
			downloadFile.flush();
			downloadFile.close();
			File inputFile = new File(destination);
			InputStream input;
			input = new FileInputStream(inputFile);
			byte[] byteArrayImage=readBytesFromIS(input);
			input.read(byteArrayImage);
			InputStream input3 = new ByteArrayInputStream(byteArrayImage);
			BufferedImage inputBufImage = ImageIO.read(input3);
			int w = inputBufImage.getWidth();
			int h = inputBufImage.getHeight();
			map.put("photo", new PictureRenderData(450, 450, destination));
		} catch (Exception e) {
			e.printStackTrace();
			//response.setContentType("application/text;charset=UTF-8");
		}finally {
		}
		
		map.put("att1","123");
		
		String dome = "C:\\upload\\dome\\12.docx";
		String dome1 = "C:\\upload\\dome\\file\\123.docx";
		
		map.put("dome",dome);
		map.put("dome1",dome1);
		String path = saveWord(map);
       
 }

public String saveWord(Map<String, Object> map) throws Exception 
        File file = new File(map.get("dome").toString());
        XWPFTemplate template = XWPFTemplate.compile(file).render(map);
        String path = map.get("dome1").toString();
        FileOutputStream out = new FileOutputStream(new File(path));
        template.write(out);
        out.flush();
        out.close();
        template.close();
        return path;
    }

在这里插入图片描述
如果是图片的为{{@picture}}
代码是从业务逻辑删除过来的、基本是可用的、只要了解poi的属性、很容易可以做到、如果代码有不通的地方、欢迎留言。

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Apache POI 来操作 Word 文档的表格,并且可以使用 XWPFTable 类来实现多行表格的替换。以下是一个简单的示例代码,可以将一个多行表格替换到指定位置并自动分页: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; public class ReplaceTableInWord { public static void main(String[] args) throws InvalidFormatException, IOException { // 读取 Word 文档 XWPFDocument doc = new XWPFDocument(new FileInputStream("input.docx")); // 查找指定位置的段落 List<XWPFParagraph> paragraphs = doc.getParagraphs(); int index = -1; for (int i = 0; i < paragraphs.size(); i++) { XWPFParagraph p = paragraphs.get(i); String text = p.getText(); if (text != null && text.contains("{{table}}")) { index = i; break; } } if (index >= 0) { // 删除占位符段落 doc.removeBodyElement(index); // 插入分页符 XWPFParagraph pageBreak = doc.createParagraph(); pageBreak.setPageBreak(true); // 创建新的表格并添加到后面 XWPFTable table = doc.createTable(5, 3); for (int i = 0; i < 5; i++) { XWPFTableRow row = table.getRow(i); for (int j = 0; j < 3; j++) { XWPFTableCell cell = row.getCell(j); cell.setText("row " + (i + 1) + ", col " + (j + 1)); } } // 将新表格插入到指定位置 paragraphs.add(index, table.getCTTbl().newDomNode()); } // 保存 Word 文档 doc.write(new FileOutputStream("output.docx")); doc.close(); } } ``` 在这个示例代码,我们首先读取一个 Word 文档,然后查找指定位置的段落,并删除该段落。然后,我们插入一个分页符,创建一个新的表格,并将其插入到指定位置。最后,我们将修改后的文档保存到一个新文件。 需要注意的是,这个示例代码仅仅是一个简单的示例,实际使用还需要根据具体的需求进行修改和扩展。同时,由于 Word 文档的格式比较复杂,使用 POI 操作 Word 文档时也需要一定的经验和技巧。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值