如何将数据从excel导入jTable?

Posted

技术标签:

【中文标题】如何将数据从excel导入jTable?【英文标题】:how to import datas from excel to jTable? 【发布时间】:2015-07-02 11:42:22 【问题描述】:
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 的方法,它工作正常,但我想在重新启动程序后导入这些数据,有人可以帮我解决这个问题吗?

【问题讨论】:

【参考方案1】:

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

在此线程中查看如何操作: apache poi: saving jtable to a file

编辑

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

【讨论】:

Tem 02, 2015 3:13:16 PM com.zfqjava.swing.JTableReadTableModelTask​​ done SEVERE: null java.io.FileNotFoundException: excelFileName.xls (Sistem belirtilen dosyayı bulamıyor) at java.io.FileInputStream .open(Native Method) at java.io.FileInputStream.(FileInputStream.java:138) at com.zfqjava.swing.ModelIO.readWorkBook(SourceFile:268) at com.zfqjava.swing.ReadTableModelTask​​.doInBackground(SourceFile :76) 在 com.zfqjava.swing.SwingWorker$2.run(SourceFile:136) 在 java.lang.Thread.run(Thread.java:745) 我得到这个错误伙伴 或者这也是另一个错误java.lang.IllegalArgumentException:您的InputStream既不是OLE2流,也不是OOXML流 您应该将excelFileName.xls 更改为您的File 对象或更改文件路径【参考方案2】:

//下载并插入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();
    

【讨论】:

【参考方案3】:
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();

这就是我解决问题的方法,希望对其他人有所帮助

【讨论】:

以上是关于如何将数据从excel导入jTable?的主要内容,如果未能解决你的问题,请参考以下文章

java中如何在JTable中显示excel数据

java的swing编程,Jtable的单元格如何赋值

如何将excel导入到数据窗口中

将excel数据导入SQLServer2005

如何将word导入excel

使用导入导出向导将数据从 Excel 导入 Sql Server 时,如何更改列的默认 varchar 255?