我正在使用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