Import Excel Data into JTable

以下这个例子是从界面中选择excel文件然后打开显示在jtable中

复制自http://www.jeromechan.com/%e6%9d%82%e9%94%a6/import-excel-data-into-jtable/

运行程序会出现以下界面

1

在以上窗口中,用户可以点击”Select Excel File”按钮去选择Excel文件,点击后会看到以下界面

2

Here is the jFilechooser, from this you have to choose excel file having extension “.xls”.  Otherwise following Error message will be displayed:
以上界面是用jFilechooser做的,限制了只能选择.xls的文件,如果选择了其它后缀名的文件会报以下错误内容
err

Note: If you want to go with MS Office 2007 Excel, you have to customise this code little bit.
Now  after select excel file the data in that Excel file will be shown in JTable as below:

注意:如果你想用MS Office 2007 版本Excel,你必须还要修改一点点代码。

选择了excel文件后就会显示excel中的内容,如下

4

OK For this you have to create one class called  excelTojTable.java
and paste the below code in it.
 在达到以上目的你必须添加excelTojTable.java文件,并且复制以下代码
 
 
注意:   fillData()  方法是运行动态获取excel内容的关键.
 
注意:    确保java运行成功,你必须添加 ”jxl.jar” 包.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
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();
 }

 

posted @ 2014-03-25 21:54  天行健小区  阅读(496)  评论(0编辑  收藏  举报