我正在使用apache POI 3.7。我正在尝试替换word文档(docx)中表格列的值。但是,我所做的是不断追加文档中当前值的值。但是,如果表列值为空,它将放置该值。你能给我一些想法如何解决这个问题。以下是我迄今为止所做的代码。替换Apache POI中的表列值
在此先感谢。
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();
}
}
您是否尝试过POI 3.8 beta 4? (或者甚至更好的是最近一次的夜间制作?) – Gagravarr
感谢您的回复。我试图使用相同的代码,但它仍然追加值的使用Apache POI 3.8.4(最新版本)。我找到了替换的链接,但它适用于段落。任何人都可以提供一些关于如何在表格单元格中做这个的想法? [链接] http://apache-poi.1045710.n5.nabble.com/Embed-string-data-to-docx-file-in-java-td3287560.html [链接] – jamojo
谢谢你的答案,但它似乎在尝试替换段落中的文本时它不起作用。因此,我做了这个危险的修改。感谢您的意见:\t \t \t \t p.removeRun(i); { XWPFRun rB4 = rs.get(i-1); String textB4 = rB4.getText(0); textB4 = StringUtils.remove(textB4,searchValue); rB4.setText(textB4); } – hamzali