2017-04-05 73 views
1

任何人都有一個想法如何從jtable插入數據到現有的Excel文件使用java來開發這個程序和我的場景是這樣的,jtable數據插入到Excel中,但Excel已經有一個設計和公式。我不知道如何開始它,所以我問問題。感謝您的提示。jtable數據插入excel

回答

1

首先,您需要從JTable提取數據。你這種方法:

public Object[][] getTableData (JTable table) { 
    DefaultTableModel dtm = (DefaultTableModel) table.getModel(); 
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount(); 
    Object[][] tableData = new Object[nRow][nCol]; 
    for (int i = 0 ; i < nRow ; i++) 
     for (int j = 0 ; j < nCol ; j++) 
      tableData[i][j] = dtm.getValueAt(i,j); 
    return tableData; 
} 

現在有了數據,你可以將它們附加到使用apache poi的excel文件。這裏是教程http://poi.apache.org/spreadsheet/quick-guide.html

+0

我要插入數據到令人興奮的excel文件? – LyodMichael

2

Excel使用複雜的格式爲其本機.xls文件,但它也支持其他格式。我使用Tab-Separated Values(TSV),通常用於將數據庫程序中的信息傳輸到電子表格。

您可以使用下面的代碼從Jtable中提取數據並將其導出爲ex​​cel。

public void toExcel(JTable table, File file) { 

try { 
    TableModel model = table.getModel(); 
    FileWriter excel = new FileWriter(file); 

    for (int i = 0; i < model.getColumnCount(); i++) { 
     excel.write(model.getColumnName(i) + "\t"); 
    } 

    excel.write("\n"); 

    for (int i = 0; i < model.getRowCount(); i++) { 
     for (int j = 0; j < model.getColumnCount(); j++) { 
      excel.write(model.getValueAt(i, j).toString() + "\t"); 
     } 
     excel.write("\n"); 
    } 

    excel.close(); 

} catch (IOException e) { 
    System.out.println(e); 
    } 
}