如何将数据从excel导入到jTable?

时间:2015-07-02 11:42:22

标签: java swing jtable jfilechooser import-from-excel

JFileChooser fc = new JFileChooser();
    int option = fc.showSaveDialog(NewJFrame1.this);
    if(option == JFileChooser.APPROVE_OPTION){
        String filename = fc.getSelectedFile().getName();
        String path = fc.getSelectedFile().getParentFile().getPath();

        int len = filename.length();
        String ext = "";
        String file = "";

        if(len > 4){
            ext = filename.substring(len-4, len);
        }

        if(ext.equals(".xls")){
            file = path + "\\" + filename; 
        }else{
            file = path + "\\" + filename + ".xls"; 
        }
        toExcel(jTable1, new File(file));


    }

这是我如何保存我的表格excel它工作正常,但我想重新启动我的程序导入这些数据可以有人帮我这个吗?

3 个答案:

答案 0 :(得分:1)

您可以使用Apache POI导出JTable数据。

在这个帖子中看看如何做到这一点: apache poi: saving jtable to a file

修改

我没有阅读您的问题,如果您尝试导入数据,请尝试以下方法: http://www.zfqjava.com/article/How-to-import-excel-into-JTabel.html

答案 1 :(得分:1)

//下载并插入jxl-1.0.jar文件

public class excelTojTable extends JFrame {

    static JTable table;
    static JScrollPane scroll;
    // header is Vector contains table Column
    static Vector headers = new Vector();
    // Model is used to construct JTable
    static DefaultTableModel model = null;
    // data is Vector contains Data from Excel File
    static Vector data = new Vector();
    static JButton jbClick;
    static JFileChooser jChooser;
    static int tableWidth = 0; // set the tableWidth
    static int tableHeight = 0; // set the tableHeight

    public excelTojTable() {
        super("Import Excel To JTable");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(Color.white);
        jChooser = new JFileChooser();
        jbClick = new JButton("Select Excel File");
        buttonPanel.add(jbClick, BorderLayout.CENTER);
        // Show Button Click Event
        jbClick.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                jChooser.showOpenDialog(null);

                File file = jChooser.getSelectedFile();
                if (!file.getName().endsWith("xls")) {
                    JOptionPane.showMessageDialog(null,
                            "Please select only Excel file.",
                            "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    fillData(file);
                    model = new DefaultTableModel(data,
                            headers);
                    tableWidth = model.getColumnCount()
                            * 150;
                    tableHeight = model.getRowCount()
                            * 25;
                    table.setPreferredSize(new Dimension(
                            tableWidth, tableHeight));

                    table.setModel(model);
                }
            }
        });

        table = new JTable();
        table.setAutoCreateRowSorter(true);
        model = new DefaultTableModel(data, headers);

        table.setModel(model);
        table.setBackground(Color.pink);

        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setEnabled(false);
        table.setRowHeight(25);
        table.setRowMargin(4);

        tableWidth = model.getColumnCount() * 150;
        tableHeight = model.getRowCount() * 25;
        table.setPreferredSize(new Dimension(
                tableWidth, tableHeight));

        scroll = new JScrollPane(table);
        scroll.setBackground(Color.pink);
        scroll.setPreferredSize(new Dimension(300, 300));
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(buttonPanel,
                BorderLayout.NORTH);
        getContentPane().add(scroll,
                BorderLayout.CENTER);
        setSize(600, 600);
        setResizable(true);
        setVisible(true);
    }

    /**
     * Fill JTable with Excel file data.
     *
     * @param file file :contains xls file to display in jTable
     */
    void fillData(File file) {

        Workbook workbook = null;
        try {
            try {
                workbook = Workbook.getWorkbook(file);
            } catch (IOException ex) {
                Logger.getLogger(
                        excelTojTable.class.
                        getName()).log(Level.SEVERE,
                                null, ex);
            }
            Sheet sheet = workbook.getSheet(0);

            headers.clear();
            for (int i = 0; i < sheet.getColumns(); i++) {
                Cell cell1 = sheet.getCell(i, 0);
                headers.add(cell1.getContents());
            }

            data.clear();
            for (int j = 1; j < sheet.getRows(); j++) {
                Vector d = new Vector();
                for (int i = 0; i < sheet.getColumns(); i++) {

                    Cell cell = sheet.getCell(i, j);

                    d.add(cell.getContents());

                }
                d.add("\n");
                data.add(d);
            }
        } catch (BiffException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        new excelTojTable();
    }
}

答案 2 :(得分:0)

try {
    jxl.Workbook workbook = jxl.Workbook.getWorkbook(file);
    jxl.Sheet sheet = workbook.getSheet(0);
    headers.clear();
    for (int i = 0; i < sheet.getColumns(); i++) {
        jxl.Cell cell1 = sheet.getCell(i, 0);
        headers.add(cell1.getContents());
    }
    data.clear();
    for (int j = 1; j < sheet.getRows(); j++) {
        Vector d = new Vector();
        for (int i = 0; i < sheet.getColumns(); i++) {
            jxl.Cell cell = sheet.getCell(i, j);
            d.add(cell.getContents());
        }
        d.add("\n");
        data.add(d);
    }
}
catch (Exception e) {
    e.printStackTrace();
}

这就是我如何解决我的问题,我希望它可以帮助别人