当前页面: 开发资料首页 → Netbeans 专题 → How to Work with Excel Files Using NetBeans
摘要: This document shows you how to use NetBeans IDE 5.0 and Java Excel library together, to create Excel-aware Java applications with ease. The document mainly describes NetBeans support for writing applications with external libraries - Excel library is not described in depth itself. For more information on working with NetBeans IDE, see the Support and Docs page on the NetBeans website, for more information about the library see JExcelApi library home page.
You create and run a simple Java application which can open an Excel spreadsheet XLS file and display its content in a table. The application uses the JExcelApi library to load Excel files and standard Swing components for UI.
Expected duration: 30 minutes
This tutorial assumes you have some basic knowledge of, or programming experience with, the following technologies.
Before you begin, you need to install the following software on your computer:
In this exercise you'll create NetBeans project and integrate it with installed Excel library.
The project is created and now it's time to configure NetBeans IDE to use the JExcelAPI library.
Now JExcelApi library is nicely integrated into your NetBeans ReadExcel project and you have full and comfortable control over its classes, sources and documentation. As a test, you can check following possibilities:
Note that process of mapping specific library, described above, can be used generally to map any library with classes and/or sources.
You configured the JExcelApi library for use in NetBeans IDE and created a project which uses the library, making coding against the library easy.
We are now prepared to design the UI of the application using the NetBeans Form Designer and to write simple code that uses JExcelAPi library to load and read Excel spreadsheet data.
Note that the IDE automatically places the JTable inside a JScrollArea. Drag the right edge of the JTable to snap to the right edge of the form. Do the same for the bottom edge of the JTable.
The basic UI is done at this point and we can continue with finally coding some functionality for our UI shell.
The basic UI is done at this point and we can continue with finally coding some functionality into our UI shell. Add all code snippets mentioned below into the appropriate places in the ReadExcelUI.java source.
Note: If you just paste in the code, you can generate the necessary import statements by pressing Alt+Shift-F at any time.
File file = chooseExcelFile(); // do nothing if open dialog was cancelled if (file == null) { return; } // loading long excel tables may be time consuming, so use wait cursor setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Sheet sheet = readExcelSheet(file); if (sheet != null) { displaySheet(sheet, jTable1); } setCursor(Cursor.getDefaultCursor());
/** Reads given excel file and returns its first sheet. * * @param file Input excel spreadsheet file * @return First sheet or null if file can't be read or have no sheets */ private Sheet readExcelSheet (File file) { // open excel file (workbook) for reading Workbook wbk; try { wbk = Workbook.getWorkbook(file); } catch (Exception ex) { JOptionPane message = new JOptionPane( "Can't read excel file " + file.getPath(), JOptionPane.ERROR_MESSAGE); return null; } if (wbk.getNumberOfSheets() <= 0) { JOptionPane message = new JOptionPane( "Excel file doesn't have any sheets.", JOptionPane.ERROR_MESSAGE); return null; } // return first sheet return wbk.getSheet(0); }
/** Takes given sheet data and displays them in very simple way in * given table. * * @param sheet Excel sheet * @param table JTable to display sheet data in */ private void displaySheet(Sheet sheet, JTable table) { table.setModel(new SheetTableModel(sheet)); } /** Read-only TableModel implementation, which adapts Sheet object from * JExcelApi library for use as JTable model. */ private static class SheetTableModel implements TableModel { private Sheet sheet; public SheetTableModel (Sheet sheet) { this.sheet = sheet; } public int getRowCount() { return sheet.getRows(); } public int getColumnCount() { return sheet.getColumns(); } /** Copied from javax.swing.table.AbstractTableModel, * to name columns using spreadsheet conventions: * A, B, C, . Z, AA, AB, etc. */ public String getColumnName(int column) { String result = ""; for (; column >= 0; column = column / 26 - 1) { result = (char)((char)(column%26)+'A') + result; } return result; } public Class<?> getColumnClass(int columnIndex) { return String.class; } public boolean isCellEditable(int rowIndex, int columnIndex) { // table is read only for demo purposes return false; } public Object getValueAt(int rowIndex, int columnIndex) { Cell cell = sheet.getCell(columnIndex, rowIndex); return cell.getContents(); } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { // no operation, table is read only for demo purposes } public void addTableModelListener(TableModelListener l) { // no operation, table is read only for demo purposes } public void removeTableModelListener(TableModelListener l) { // no operation, table is read only for demo purposes } } // end of SheetTableModel
These were the most interesting parts of the code, and our application is now able to load and display Excel files.
To complete our small application, we need to let the user choose the Excel file that is read and add some other final touches, so let's go for it.
/** Opens dialog for user to choose an excel file to open and read. * * @return Excel file or null if user cancelled the dialog */ private File chooseExcelFile () { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new XLSFilter()); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { return chooser.getSelectedFile(); } // cancel was clicked return null; } /** Filter which accepts only xls files */ private static class XLSFilter extends FileFilter { public boolean accept(File f) { return f.isDirectory() || f.getName().endsWith(".xls"); } public String getDescription() { return "Excel spreadsheet XLS files"; } }
dispose(); System.exit(0);
That's it, congratulation! I hope that is all you need for the start. In case something goes wrong, you can compare your code agains the complete source code of ReadExcelUI.java and also open and run the complete exercise solution. Note that the project doesn't contain JExcelApi library binary, so you have to download it and specify the location of the binary.
You just wrote and tested a simple application which reads and displays Excel *.xls spreadsheet files using NetBeans IDE and the JExcelApi library.
To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE development features, join the mailing list.