我需要从 word 文档中检索具有与我的文档中相同的表结构的表。即我想要一个有行和列的表。
目前我使用的代码工作正常,但它只提供单元格内的文本,这些文本太没有格式化方式。是否有任何可能的方法来获取具有我文档中的表结构的整个表。
以下是我用来读取表格的代码
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class TableTest {
public static void main(String args[]) throws IOException
{
String fileName="D:\\vignesh\\model.doc";
InputStream fis=new FileInputStream(fileName);
POIFSFileSystem fs=new POIFSFileSystem(fis);
HWPFDocument doc=new HWPFDocument(fs);
Range range=doc.getRange();
for(int i=0;i<range.numParagraphs();i++)
{
Paragraph par=range.getParagraph(i);
System.out.println(par.text());
}
Paragraph tablePar=range.getParagraph(0);
if(tablePar.isInTable())
{
Table table=range.getTable(tablePar);
for(int rowIdx=0;rowIdx<table.numRows();rowIdx++)
{
TableRow row=table.getRow(rowIdx);
System.out.println("row "+(rowIdx+1)+",is table header: "+row.isTableHeader());
for(int colIdx=0;colIdx<row.numCells();colIdx++)
{
TableCell cell=row.getCell(colIdx);
System.out.println("column "+(colIdx+1)+",text= "+cell.getParagraph(0).text());
}
}
}
}
}
我需要检索整个表格及其单元格,并且必须将其传递给另一个类,该类将使用该表格创建 PDF 文档。任何检索表格的示例代码对我来说都非常有帮助。