Apache POI:将JTable保存到文件

6

我最近开始使用Java,但在创建jTable的Excel文件时遇到了一些Apache POI库的问题。

我阅读了许多线程并编写了一些代码,但无法正常运行(即使这是相当简单的内容,并且有许多示例,这让我看起来更加愚蠢),因此我希望有人能帮助我。

所以这里有几个问题:

a)为什么用于编写Excel文件的for循环不会填充每个单元格?(Excel文件中唯一有数据的行是第六行,这也让我想知道为什么在获取getRowCount / Column方法的表模型中计算null项..还要注意它打印自定义字符串而不是表本身,但保存这个信息作为点b)

b)我该如何使用jtable模型项来填充Excel文件,因为在创建表时,我必须选择Object作为行类型?(我还遇到了某种对象的问题,只要它是String || integer,就没有任何问题,但表应该混合两者,当您尝试使用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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//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", "x-y"},
                {"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();
    }// </editor-fold>//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
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * 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);
        }
        //</editor-fold>

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

附注: 如果你想知道我为什么使用对象类型来构建表格: 这并不是我正在处理的项目,我制作了这个片段来测试hssf,因为生成的Excel非常容易编辑,但事情似乎并不顺利。

另外:我尝试使用tokenizer类,但我不确定您是否可以像poi lib那样编辑生成的Excel文件。

再者:这是我第一次尝试使用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());
        } 
    } 

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

再次感谢提示,它们真的起到了作用^^

2个回答

5
请阅读有关 JTable创建表格模型实现的数据类型的教程。对于大多数在 MS Excel 中的类型,JTable 知道这些 Column Classes,并返回适当的值以输出到 POI
  1. 你需要循环遍历当前行中的单元格

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

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

通过 TableModel 循环的代码也可以使用标准的 windows分隔符 生成 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();
    }
}

谢谢,这真的会帮到我。我想我还需要再阅读一些教程,因为我似乎没有完全掌握事物的工作原理 :P - Marchius

2

我知道这篇文章可能有点晚了,但如果其他人需要这段代码,这里是可行的代码。

    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);
    }

希望这能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接