apache poi:将jtable保存到文件中

我最近开始使用java,当我需要从jTable开始创建一个excel文件时,我遇到了apache poi库的一些问题。

我已经阅读了许multithreading,并提出了一些不起作用的代码(即使这很简单,有很多例子,这让我看起来更愚蠢)而且我希望有人可以帮助我。

以下是问题:

a)为什么写入excel文件的for循环不填充每个单元格? (excel文件中唯一包含数据的行是第六行,这也让我想知道为什么它会计算getRowCount / Column方法的表模型中的空项。所以我知道它打印的是自定义String而不是表本身,但保留点b)

b)我应该如何使用jtable模型项来填充excel文件,因为在创建表时我必须选择Object作为行类型? (我也遇到了这类对象的问题,只要它是一个字符串||整数就没有任何问题,但是这个表应该是两者的混合,当你尝试时它似乎不起作用使用setCellValue()方法与String || integer …或至少我无法使其工作的东西

c)让我说我以后想要从我之前创建的文件中填充jtable,在使用bufferedReader类读取文件后,我是否只需要使用解决方案指向b)(另一种方法)?

免责声明:代码的第一部分是由netbeans自动生成的,你可以告诉我,我想出的hssf部分是在最后,但我想你可能想要看到整件事,抱歉,如果它看起来有点凌乱。

这是代码:

package poitest; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JTable; import javax.swing.table.TableModel; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; public class POITestFrame extends javax.swing.JFrame { /** * Creates new form POITestFrame */ public POITestFrame() { initComponents(); } @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { excelButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); excelButton.setText("ESPORTA!"); excelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { excelButtonActionPerformed(evt); } }); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"Boolean", "Integer", "String", "Array"}, {"x*y", "x+y", "x/y", "xy"}, {"32", "43", "12", "24"}, {"casa", "cantiere", "museo", "acquario"}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE) .addComponent(excelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(excelButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// //GEN-END:initComponents private void excelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_excelButtonActionPerformed try { PoiWriter(jTable1); } catch (FileNotFoundException ex) { Logger.getLogger(POITestFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(POITestFrame.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_excelButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ // /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new POITestFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton excelButton; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables private void PoiWriter(JTable jTable1) throws FileNotFoundException, IOException { TableModel model = jTable1.getModel(); // create a workbook Workbook wb = new HSSFWorkbook(); // xls file // create a new sheet Sheet sheet = wb.createSheet("Foglio di Prova!"); // declare a row object reference Row r = null; // declare a cell object reference Cell c = null; // create a new file FileOutputStream fos; fos = new FileOutputStream("File di Prova.xls"); // create a sheet table rows int rownum; for (rownum = (short) 0; rownum < model.getRowCount(); rownum++) { // create a row r = sheet.createRow(rownum); } for (short cellnum = (short) 0; cellnum < model.getRowCount(); cellnum ++) { // create a numeric cell c = r.createCell(cellnum); // populate table with custom objects for(int i=0; i < model.getRowCount();i++){ for(int j=0;j < model.getColumnCount();j++){ String aplala = "blabla"; c.setCellValue(aplala); } } } wb.write(fos); fos.close(); } } 

PS:如果你想知道为什么我用对象类型构建表:这不是我正在使用的项目,我制作了这个片段来测试hssf,因为得到的excel是非常可编辑的但似乎没有顺利

PPS:我也尝试过使用tokenizer类,但我不确定你是否可以像使用poi lib一样编辑生成的excel文件。

PPPS:这是我对java的第一次尝试所以,请不要太粗暴!

我希望这些问题足够清楚,并且事先感谢,我正努力在编程方面做得更好:P

编辑:经过一天的练习后,这就是我想出来的,似乎与apache poi库一起工作,感谢帮助人们提供了很好的指示!

  int rowNum; int colNum; int tempRows; int rowCount = model.getRowCount(); int columnCount = model.getColumnCount(); // create the headers for (colNum = 0; colNum < columnCount; colNum++) { if (colNum == 0) { r = sheet.createRow(0); } c = r.createCell(colNum); c.setCellValue(model.getColumnName(colNum)); } for (rowNum = 0; rowNum < rowCount; rowNum++) { // create rows + 1 (to account for the headers) tempRows = rowNum + 1; r = sheet.createRow(tempRows); for (short cellnum = 0; cellnum < columnCount; cellnum ++) { // create cells c = r.createCell(cellnum); // add values from table c.setCellValue(model.getValueAt(rowNum, cellnum).toString()); } } 

如果您认为代码可以改进,请随时发表评论,欢迎提出建议,特别是像我这样的新人;)

再次,感谢您的提示,他们真的做到了^^

请阅读有关JTable , 创建表模型和实现数据类型的教程, JTable知道那些Column Classes ,并返回输出到POI proper value ; 对于MS Excel中的大多数类型:

  1. 你也必须在当前行的单元格内循环

  2. 必须格式化各种数据类型的输出( DateDoubleString

  3. 然后你可以专注于创建formula(s)coloring cell(s)

循环使用TableModel代码也可以使用标准的windows delimiters生成MS Excel文件:

 public class ExcelCustomerReport { public ExcelCustomerReport() { } public void exportTable(JTable table, File file) throws IOException { TableModel model = table.getModel(); FileWriter out = new FileWriter(file); String groupExport = ""; for (int i = 0; i < (model.getColumnCount()); i++) {//* disable export from TableHeaders groupExport = String.valueOf(model.getColumnName(i)); out.write(String.valueOf(groupExport) + "\t"); } out.write("\n"); for (int i = 0; i < model.getRowCount(); i++) { for (int j = 0; j < (model.getColumnCount()); j++) { if (model.getValueAt(i, j) == null) { out.write("null" + "\t"); } else { groupExport = String.valueOf(model.getValueAt(i, j)); out.write(String.valueOf(groupExport) + "\t"); } } out.write("\n"); } out.close(); } } 

我知道这个post可能已经晚了,但也许对于其他想要代码的人来说,这里有一些有用的东西。

  TableModel model = raportTable.getModel(); SXSSFWorkbook wb = new SXSSFWorkbook(-1); SXSSFSheet sh = wb.createSheet("Report"); Row row = sh.createRow(0); for (int i = 0; i < model.getColumnCount(); i++) { Cell cell = row.createCell(i); cell.setCellValue(model.getColumnName(i)); } for(int i = 0; i < model.getRowCount(); i++) { row = sh.createRow(i + 1); for(int j = 0; j < model.getColumnCount(); j++){ Cell cell = row.createCell(j); cell.setCellValue(model.getValueAt(i,j).toString()); } } try { FileOutputStream excel = new FileOutputStream(filename + ".xlsx"); wb.write(excel); excel.flush(); excel.close(); } catch (FileNotFoundException ex) { Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex); } 

希望能帮助到你。