替换 Apache POI 中的表列值 [英] Replace table column value in Apache POI

查看:48
本文介绍了替换 Apache POI 中的表列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 apache POI 3.7.我正在尝试替换 word 文档 (docx) 中表列的值.但是,我所做的是不断在文档中附加当前值的值.但如果表列值为空,则会放置该值.你能给我一些想法如何解决这个问题.下面是我到目前为止所做的代码.

I am using apache POI 3.7. I am trying to replace the value of a table column in a word document (docx). However, what I have done is it keeps appending the value of the current value in the document. But if a table column value is null, it places the value. Can you give me some thoughts how to resolve this. Below is the code I have done so far.

提前致谢.

package test.doc;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class POIDocXTableTest {

    public static void main(String[] args)throws IOException {
        String fileName = "C:\\Test.docx";
        InputStream fis = new FileInputStream(fileName);
        XWPFDocument document = new XWPFDocument(fis);
        List<XWPFParagraph> paragraphs = document.getParagraphs();

        for (int x=0; x<paragraphs.size();x++)
        {
            XWPFParagraph paragraph = paragraphs.get(x);
            System.out.println(paragraph.getParagraphText());
        }
        List<XWPFTable> tables = document.getTables();
        for (int x=0; x<tables.size();x++)
        {
            XWPFTable table = tables.get(x);
            List<XWPFTableRow> tableRows = table.getRows();
            tableRows.remove(x);
            for (int r=0; r<tableRows.size();r++)
            {
                System.out.println("Row "+ (r+1)+ ":");
                XWPFTableRow tableRow = tableRows.get(r);
                List<XWPFTableCell> tableCells = tableRow.getTableCells();
                for (int c=0; c<tableCells.size();c++)
                {
                    System.out.print("Column "+ (c+1)+ ": ");
                    XWPFTableCell tableCell = tableCells.get(c);
                    //tableCell.setText("TAE");
                    String tableCellVal = tableCell.getText();
                    if ((c+1)==2){
                        if (tableCellVal!=null){
                            if (tableCellVal.length()>0){
                                 char c1 = tableCellVal.charAt(0);
                                 String s2 = "-TEST";
                                 char c2 = s2.charAt(0);
                                 String test = tableCell.getText().replace(tableCellVal,s2);
                                 tableCell.setText(test);
                            }else{
                                //tableCell.setText("NULL");
                            }
                        }
                    }
                    System.out.println("tableCell.getText(" + (c) + "):" + tableCellVal);
                }
            }
            System.out.println("\n");
        }
        OutputStream out = new FileOutputStream(fileName);
        document.write(out);
        out.close();
    }
}

推荐答案

防止段落样式和查找不同样式的搜索字符串的最佳解决方案是这种方法:

The best solution to prevent styles in paragraphs and find search strings with different styles is this method:

  private long replaceInParagraphs(Map<String, String> replacements, List<XWPFParagraph> xwpfParagraphs) {
    long count = 0;
    for (XWPFParagraph paragraph : xwpfParagraphs) {
      List<XWPFRun> runs = paragraph.getRuns();

      for (Map.Entry<String, String> replPair : replacements.entrySet()) {    
        String find = replPair.getKey();
        String repl = replPair.getValue();
        TextSegement found = paragraph.searchText(find, new PositionInParagraph());
        if ( found != null ) {
          count++;
          if ( found.getBeginRun() == found.getEndRun() ) {
            // whole search string is in one Run
           XWPFRun run = runs.get(found.getBeginRun());
           String runText = run.getText(run.getTextPosition());
           String replaced = runText.replace(find, repl);
           run.setText(replaced, 0);
          } else {
            // The search string spans over more than one Run
            // Put the Strings together
            StringBuilder b = new StringBuilder();
            for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
              XWPFRun run = runs.get(runPos);
              b.append(run.getText(run.getTextPosition()));
            }                       
            String connectedRuns = b.toString();
            String replaced = connectedRuns.replace(find, repl);

            // The first Run receives the replaced String of all connected Runs
            XWPFRun partOne = runs.get(found.getBeginRun());
            partOne.setText(replaced, 0);
            // Removing the text in the other Runs.
            for (int runPos = found.getBeginRun()+1; runPos <= found.getEndRun(); runPos++) {
              XWPFRun partNext = runs.get(runPos);
              partNext.setText("", 0);
            }                          
          }
        }
      }      
    }
    return count;
  }

此方法适用于跨越多个 Run 的搜索字符串.被替换的部分从第一个找到的 Run 中获取样式.

This method works with search strings spanning over more than one Run. The replaced part gets the style from the first found Run.

这篇关于替换 Apache POI 中的表列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆