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

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

问题描述

我使用Apache POI 3.7。我试图取代一个word文档(DOCX)在表列中的值。不过,我所做的是它使附加文档中的当前值的值。但是,如果一个表列值为null,它把价值。你能给我一些想法如何解决这个问题。下面是code到目前为止,我已经做了。

先谢谢了。

 包Test.doc的;
进口java.io.FileInputStream中;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口的java.util.List;进口org.apache.poi.xwpf.usermodel.XWPFDocument;
进口org.apache.poi.xwpf.usermodel.XWPFParagraph;
进口org.apache.poi.xwpf.usermodel.XWPFTable;
进口org.apache.poi.xwpf.usermodel.XWPFTableCell;
进口org.apache.poi.xwpf.usermodel.XWPFTableRow;公共类POIDocXTableTest {    公共静态无效的主要(字串[] args)抛出IOException
        字符串文件名=C:\\\\ Test.docx
        InputStream的FIS =新的FileInputStream(文件名);
        XWPFDocument文档=新XWPFDocument(FIS);
        清单< XWPFParagraph>段= document.getParagraphs();        为(中间体X = 0; X&下; paragraphs.size(); X ++)
        {
            XWPFParagraph款= paragraphs.get(X);
            的System.out.println(paragraph.getParagraphText());
        }
        清单< XWPFTable>表= document.getTables();
        为(中间体X = 0; X&下; tables.size(); X ++)
        {
            XWPFTable表= tables.get(X);
            清单< XWPFTableRow> tableRows = table.getRows();
            tableRows.remove(X);
            对于(INT R = 0;为r tableRows.size(); R ++)
            {
                的System.out.println(行+(R + 1)+:);
                XWPFTableRow的TableRow = tableRows.get(R);
                清单< XWPFTableCell> tableCells = tableRow.getTableCells();
                对于(INT C = 0; C< tableCells.size(); C ++)
                {
                    System.out.print(列+(C + 1)+:);
                    XWPFTableCell的TableCell = tableCells.get(C);
                    //tableCell.setText(\"TAE);
                    串tableCellVal = tableCell.getText();
                    如果((C + 1)== 2){
                        如果(tableCellVal!= NULL){
                            如果(tableCellVal.length()大于0){
                                 炭C1 = tableCellVal.charAt(0);
                                 字符串s2 =试验;
                                 炭C2 = s2.charAt(0);
                                 字符串测试= tableCell.getText()取代(tableCellVal,S2)。
                                 tableCell.setText(试验);
                            }其他{
                                //tableCell.setText(\"NULL);
                            }
                        }
                    }
                    的System.out.println(tableCell.getText(+(C)+):+ tableCellVal);
                }
            }
            的System.out.println(\\ n);
        }
        出的OutputStream =新的FileOutputStream(文件名);
        文件撰写(出);
        out.close();
    }
}


解决方案

在段落prevent风格的最佳解决方案,并找到不同风格的搜索字符串是此方法:

 私人长期replaceInParagraphs(地图<字符串,字符串>替补,列表与LT; XWPFParagraph> xwpfParagraphs){
    长计数= 0;
    对于(XWPFParagraph段:xwpfParagraphs){
      清单< XWPFRun>奔跑= paragraph.getRuns();      对于(Map.Entry的<字符串,字符串> replPair:replacements.entrySet()){
        字符串找到= replPair.getKey();
        字符串REPL = replPair.getValue();
        TextSegement发现= paragraph.searchText(找到新PositionInParagraph());
        如果(发现!= NULL){
          算上++;
          如果(found.getBeginRun()== found.getEndRun()){
            //整个搜索字符串是在一个运行
           XWPFRun运行= runs.get(found.getBeginRun());
           串runText = run.getText(run.getTextPosition());
           字符串替代= runText.replace(查找,REPL);
           run.setText(取代,0);
          }其他{
            //搜索字符串跨越一个以上的运行
            //把字符串连接在一起
            StringBuilder的B =新的StringBuilder();
            对(INT runPos = found.getBeginRun(); runPos&下; = found.getEndRun(); runPos ++){
              XWPFRun运行= runs.get(runPos);
              在b.append(run.getText(run.getTextPosition()));
            }
            串connectedRuns = b.toString();
            字符串替代= connectedRuns.replace(查找,REPL);            //第一次运行接收所有连接运行的替换字符串
            XWPFRun partOne = runs.get(found.getBeginRun());
            partOne.setText(取代,0);
            //删除在其他运行文本。
            对(INT runPos = found.getBeginRun()+ 1; runPos&下; = found.getEndRun(); runPos ++){
              XWPFRun partNext = runs.get(runPos);
              partNext.setText(,0);
            }
          }
        }
      }
    }
    返回计数;
  }

此方法适用于搜索字符串跨越一个以上的运行。将被替换部分从第一个找到的运行得到的风格。

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.

Thanks in advance.

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;
  }

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天全站免登陆