EDITED将JTable写入Excel

时间:2017-04-23 02:27:05

标签: java excel eclipse swing jtable

我正在尝试将我的JTable导出到Excel文件。列和行名称都很好,但我在JTable中添加的所有信息都没有写入。我尝试了 System.out.println(),除了列名和行名之外,它还打印了 Null 值。我试图从谷歌谷歌得到答案,但经过2个小时的阅读和尝试,仍然没有进展。  我脑子里的问题是,在写入Excel部分的代码中可能存在一些错误,或者添加到JTable的所有内容只是我显示器上的图片,而不是其中的实际数据。 如果我错了,请纠正我,并且非常感谢任何帮助。

这是写入Excel部分。 在第一个For循环中我得到标题,在第二个For循环中,我应该得到我的JTable中的所有内容,但我不是。

TableColumnModel tcm = nrp.rotaTable.getColumnModel();

    String nameOfFile = JOptionPane.showInputDialog("Name of the file");

    Workbook wb = new HSSFWorkbook();
    CreationHelper createhelper = wb.getCreationHelper();

    Sheet sheet = wb.createSheet("new sheet");
    Row row = null;
    Cell cell = null;

    for (int i = 0; i < nrp.tableModel.getRowCount(); i++) {
        row = sheet.createRow(i);
        for (int j = 0; j < tcm.getColumnCount(); j++) {

            cell = row.createCell(j);
            cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());

        }
    }
    for (int i = 1; i < nrp.tableModel.getRowCount(); i++) {
        row = sheet.createRow(i);
        System.out.println("");
        for (int j = 0; j < nrp.tableModel.getColumnCount(); j++) {

            cell = row.createCell(j);
            cell.setCellValue((String) nrp.tableModel.getValueAt(i, j)+" ");
            System.out.print((String) nrp.tableModel.getValueAt(i, j)+" ");
        }
    }


    File file = new File("Some name.xls");
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
    wb.close();
  }
}

这是FocusListener代码。

rotaTable.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {
            }
            public void focusLost(FocusEvent e) {
                CellEditor cellEditor = rotaTable.getCellEditor();
                if (cellEditor != null)
                    if (cellEditor.getCellEditorValue() != null)
                        cellEditor.stopCellEditing();
                    else
                        cellEditor.cancelCellEditing();
            }
        });

我正在使用&#39; DefaultTableModel&#39;

 DefaultTableModel tableModel = new DefaultTableModel(12,8); 
JTable rotaTable = new JTable(tableModel); 

这是我第一次使用POI库。

我的JTable图片http://imgur.com/a/jnB8j

打印结果图片在控制台http://imgur.com/a/jnB8j

创建的Excel文件的图片。 http://imgur.com/a/jnB8j

3 个答案:

答案 0 :(得分:4)

你必须将行索引开始为0,因为表行从0开始并从1创建excel行,因为首先为你写了列名。我修改了你的第二个for循环:

for (int i= 0; i < nrp.tableModel.getRowCount(); i++) {
    row = sheet.createRow(i+1);
    System.out.println("");
    for (int j = 0; j < nrp.tableModel.getColumnCount(); j++) {
        cell = row.createCell(j);
        if(nrp.tableModel.getValueAt(i, j)!=null){
        cell.setCellValue((String) nrp.tableModel.getValueAt(i, j));
        }
        System.out.print((String) nrp.tableModel.getValueAt(i, j)+" ");
    }
}

答案 1 :(得分:1)

编写此代码后,用于将一组JTable写入Excel文件(一个接一个)。 正如我所看到的,它实际上与您编写的代码相同。你可以试试这个而不是你阻止。您必须替换Entry对象或将表格包装到Map

for (int i = 1; i < nrp.tableModel.getRowCount(); i++) {
...
}

由于我需要一个接一个地写表,我使用变量fila和columna来获取当前位置以放置下一个表。 您可以将它们设置为0或1以进行测试。 也许它可以帮助你带来新的想法。

我注意到的唯一区别是:     if(row == null){...}

private void escribirContenido(Sheet hoja, Entry<String, JTable> e) {
    Row row;
    Cell cell;
    for (int i = fila; i < e.getValue().getRowCount() + fila; i++) {
        row = hoja.getRow(i);
        if (row == null) {
            row = hoja.createRow(i);
        }
        for (int j = 0; j < e.getValue().getColumnCount(); j++) {
            cell = row.createCell(j + columna);
            String value = String.valueOf(e.getValue().getValueAt(i - fila, j));
            try {
                cell.setCellValue(new Double(value));
            } catch (NumberFormatException e1) {
                cell.setCellValue(value);
            }
        }
    }
}

答案 2 :(得分:0)

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

@SuppressWarnings("serial")
public class EmployeePanel extends JPanel {
    public ArrayList columnNames = new ArrayList();
    ArrayList data = new ArrayList();
    Connection conn;
    String query;
    String sql = "SELECT * FROM employee";
    String url = "jdbc:mysql://localhost:3306/nandos_db";
    String userid = "User1";
    String password = "Password1";
    Statement stmt;
    ResultSet rs;
    int rows = 0;
    int columns = 0;
    JTable employeeTable;

    @SuppressWarnings({ "unchecked" })
    public EmployeePanel() {
        super();
        this.setBackground(Color.GREEN);
        this.setLayout(null);
        this.setVisible(true);
        try {
            conn = DriverManager.getConnection(url, userid, password);
            stmt = (Statement) conn.createStatement();
            rs = stmt.executeQuery(sql);
            ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();

            int columns = md.getColumnCount();
            for (int i = 1; i <= 3; i++) {
                columnNames.add(md.getColumnName(i));
            }
            while (rs.next()) {
                ArrayList row = new ArrayList(columns);
                for (int i = 1; i <= columns; i++) {
                    row.add(rs.getObject(i));
                }
                data.add(row);
            }
            // Get row data
        } catch (SQLException e) {
            // System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // Create Vectors and copy over elements from ArrayLists to them
        // a custom defined class which inherits from the AbstractTableModel
        // class
        Vector columnNamesVector = new Vector();
        Vector dataVector = new Vector();
        for (int i = 0; i < data.size(); i++) {
            ArrayList subArray = (ArrayList) data.get(i);
            Vector subVector = new Vector();
            for (int j = 0; j < subArray.size(); j++) {
                subVector.add(subArray.get(j));
            }
            dataVector.add(subVector);
        }
        for (int i = 0; i < columnNames.size(); i++) {
            columnNamesVector.add(columnNames.get(i));
        }
        // Create table with database data
        employeeTable = new JTable(dataVector, columnNamesVector);
        employeeTable.getTableHeader().setOpaque(false);
        employeeTable.getTableHeader().setBackground(Color.pink);
        employeeTable.setBackground(Color.orange);
        employeeTable.setSelectionMode((ListSelectionModel.SINGLE_SELECTION));
        employeeTable.setEnabled(true);
        employeeTable.setDragEnabled(false);
        employeeTable.setCellEditor(null);

        JScrollPane sp = new JScrollPane(employeeTable);
        sp.setSize(1030, 540);
        sp.setLocation(10, 10);
        this.add(sp);
    }

    public static void main(String... args) throws IOException {
        JFrame f = new JFrame();
        EmployeePanel t = new EmployeePanel();
        f.add(t);
        f.setVisible(true);
        f.pack();

        System.out.println(t.employeeTable.getValueAt(0, 0));

        Workbook wb = new HSSFWorkbook();
        CreationHelper createhelper = wb.getCreationHelper();

        Sheet sheet = wb.createSheet("new sheet");
        Row row = null;
        Cell cell = null;
        row = sheet.createRow(0);
        for (int i = 0; i < t.employeeTable.getColumnCount(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(String.valueOf(t.employeeTable.getColumnName(i)));
        }

        for (int j = 1; j <= t.employeeTable.getRowCount(); j++) {
            row = sheet.createRow(j);
            for (int i = 0; i < t.employeeTable.getColumnCount(); i++) {
                cell = row.createCell(i);

                cell.setCellValue(String.valueOf(t.employeeTable.getValueAt(j - 1, i)));

            }
        }

        File file = new File("C:\\Users\\test\\Desktop\\Some name.xls");
        FileOutputStream out = new FileOutputStream(file);
        wb.write(out);
        out.close();
        wb.close();

    }

}

如果我让这段代码连接到我的数据库,那么得到一张excel表格,其内容与框架中的表格完全相同。因为你显然还有一些你尚未展示的代码,你可能需要适当地调整它。这段代码在1级

中全部工作