2016-03-01 160 views
-1

我有從數據庫中獲取數據的默認表模型,我想以doc表格的形式在doc字中打印。如何實現這一點。請參見下面的代碼:用Java創建Word文檔

try { 
     try { 
      con = connCC.getDBconnection(); 
      } catch (ClassNotFoundException ex) { 
       Logger.getLogger(CustomerSR.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     stm = con.createStatement(); 
     ResultSet rs = stm.executeQuery("Select * From Appointment"); 

     while (rs.next()) { 

      for (int col = 0; col < 1; col++) { 
       rowData.add(rs.getString(1)); 
       rowData.add(rs.getString(2)); 
       rowData.add(rs.getString(3)); 
       rowData.add(rs.getString(4)); 
       rowData.add(rs.getString(5)); 
      } 
      model.addRow(rowData); 
     } 
      window.display(model); 
      //window.display(names, phones, addresses); 
     } catch (SQLException ex) { 
      ex.printStackTrace(); 
    } 

} 
+0

我將開始與Apache POI,如http://stackoverflow.com/questions/10266844/apache-poi-word-tutorial – rkosegi

+0

我不相信Java可以做到這一點對自己。你將需要尋找一個API來使用。 – Tricky12

+0

感謝Tricky12,你能推薦任何API嗎? – Meli

回答

1

在上面的評論,我看你已經使用Apache POI。如果我理解正確,您希望將數據庫中的數據輸入到Word文檔的表格中。看看這篇關於使用Apache POI創建表格的教程: http://www.tutorialspoint.com/apache_poi_word/apache_poi_word_tables.htm

您可以使用從數據庫檢索的數據直接設置文本。如果您需要它,我可以發佈一個示例,但該教程在展示您需要做的事情方面做得很好。

---- ---- UPDATE

對不起我花了一段時間,一起午餐的妻子。試試這個:

// 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(); 

// Table row 
XWPFTableRow tableRow; 

int rowCount = model.getRowCount() - 1; 
int colCount = model.getColumnCount() - 1; 

// Iterate through rows 
for (int row = 0; row <= rowCount; row++) { 
    tableRow = table.getRow(row); 

    // Iterate through columns 
    for (int col = 0; col <= colCount; col++) { 
     tableRow.getCell(col).setText((String) model.getValueAt(row, col)); 

     // If more columns, add cell 
     if (row == 0 && col < colCount) { 
      tableRow.addNewTableCell(); 
     } 
    } 

    // If more rows, add row 
    if (row < rowCount) { 
     table.createRow(); 
    } 
} 

// Write to word document and close file.   
document.write(out); 
out.close(); 
+0

JagerSOE你有我的觀點,我做了類似這個教程,但我仍然無法獲取一個單元格中的一個數據,我的代碼是在一個單元格中提取數據的一列? – Meli

+0

你的意思是它將整列的數據放入1個單元格中? – JagerSOE

+0

JagerSOE是的,數據不是有意義的 – Meli