2016-08-10 42 views
1

私はテーブルを持つ単語の文書を持っています。 Javaを使ってこれらのセルにテキストを挿入したいのですが、Apache POIをプロジェクトに追加しました。Java、Apache POIを使用してワードテーブルセルに書き込みますか?

しかし、私はドキュメントからの読み取りに成功しました。私のアプリケーションは、テーブル内のすべてのセルを取得します。しかし、私はどのように各セルに新しいテキストを挿入するのか分からない?何か案は?

String SOURCE_FILE = "template.doc"; 

    DocumentProcessor instance = new DocumentProcessor(); 
    HWPFDocument doc = null; 
    try { 
     doc = instance.openDocument(SOURCE_FILE); 

     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); 
        cell.getParagraph(0).text().replace("", "Hello"); 
        System.out.println(cell.getParagraph(0).text()); 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     saveDocument(doc, SOURCE_FILE); 

    } 
} 


private HWPFDocument openDocument(String file) throws Exception { 
    URL res = getClass().getClassLoader().getResource(file); 
    HWPFDocument document = null; 
    if (res != null) { 
     document = new HWPFDocument(new POIFSFileSystem(
       new File(res.getPath()))); 
    } 
    return document; 
} 

private static void saveDocument(HWPFDocument doc, String file) { 
    try (FileOutputStream out = new FileOutputStream(file)) { 
     doc.write(out); 
     doc.close(); 
     System.out.println("File saved"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

答えて

0
public class TableCreate{ 

public static void main(String[] args)throws Exception { 

    //Blank Document 
    XWPFDocument document= new XWPFDocument(); 

    //Write the Document in file system 
    FileOutputStream out = new FileOutputStream(
    new File("create_table.docx")); 

    //create table 
    XWPFTable table = document.createTable(); 
    //create first row 
    XWPFTableRow tableRowOne = table.getRow(0); 
    tableRowOne.getCell(0).setText("col one, row one"); 
    tableRowOne.addNewTableCell().setText("col two, row one"); 
    tableRowOne.addNewTableCell().setText("col three, row one"); 
    //create second row 
    XWPFTableRow tableRowTwo = table.createRow(); 
    tableRowTwo.getCell(0).setText("col one, row two"); 
    tableRowTwo.getCell(1).setText("col two, row two"); 
    tableRowTwo.getCell(2).setText("col three, row two"); 
    //create third row 
    XWPFTableRow tableRowThree = table.createRow(); 
    tableRowThree.getCell(0).setText("col one, row three"); 
    tableRowThree.getCell(1).setText("col two, row three"); 
    tableRowThree.getCell(2).setText("col three, row three"); 

    document.write(out); 
    out.close(); 
    System.out.println("create_table.docx written successully"); 
    } 
} 

出力

enter image description here

関連する問題