java - 在word中找到一个表并使用java在该表中写入

标签 java word-automation

我有一个 word 文档,其中可能有 n 个表格。该表由作为标题写入第一个单元格中的表名标识。现在我必须找到带有表名的表并写入该表的单元格之一。我尝试使用 apache-poi 进行相同但无法弄清楚如何将它用于我的目的。如果我无法解释文档的外观,请参阅随附的屏幕截图。

谢谢 as seen in screenshot name of tables are S1 and S2

    String fileName = "E:\\a1.doc";  

    if (args.length > 0) {  
        fileName = args[0];  
    }  

    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 tablePar = range.getParagraph(i);

        if (tablePar.isInTable()) {  
            Table table = range.getTable(tablePar);  
            for (int rowIdx=0; rowIdx<table.numRows(); rowIdx++) {  

                for (int colIdx=0; colIdx<row.numCells(); colIdx++) {  
                    TableCell cell = row.getCell(colIdx);  
                    System.out.println("column="+cell.getParagraph(0).text());  
                }  
            }  
        }  
    } 

这是我尝试过的方法,但这只读取了第一个表。

最佳答案

我发现你对 poi 有误解。 如果你只是想读取一个表。只需使用 TableIterator 来获取表的内容,否则你将得到一个没有表开始的异常。

我想每个表格单元格中只有一个段落。

    InputStream fis = new FileInputStream(fileName);  
    POIFSFileSystem fs = new POIFSFileSystem(fis);  
    HWPFDocument doc = new HWPFDocument(fs);  

    Range range = doc.getRange();
    TableIterator itr = new TableIterator(range);
    while(itr.hasNext()){
        Table table = itr.next();
        for(int rowIndex = 0; rowIndex < table.numRows(); rowIndex++){
            TableRow row = table.getRow(rowIndex);
            for(int colIndex = 0; colIndex < row.numCells(); colIndex++){
                TableCell cell = row.getCell(colIndex);
                System.out.println(cell.getParagraph(0).text());
            }
        }
    }

关于java - 在word中找到一个表并使用java在该表中写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12561527/

相关文章:

Java Finalize() 调用计数

c# - 以编程方式打印 word 文档的目录...总是跳过最后一个文件

java - 关于此异常可能来自何处的任何想法?

java - 创建仅采用值作为参数的方法,该方法实现 Comparable<T>

java - 如何 Autowiring 泛型类型

c# - 服务器上的错误 "This command is not available because no document is open"

pdf-generation - 如何以编程方式使用 Word 2007 将 Word 文件转换为 PDF?

c++ - 对打开的文档执行 Word 自动化是否安全?

java - JMockit : How to avoid code from superclasses' constructors