站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题How to Work with Excel Files Using 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

Prerequisites

This tutorial assumes you have some basic knowledge of, or programming experience with, the following technologies.

  • NetBeans IDE
  • Very basics of JExcelApi library, or any other Java Excel related library. (See also the simple Handle Excel Files tutorial which lists tools and ways of working with Excel files in Java.)

Software Needed for the Tutorial

Before you begin, you need to install the following software on your computer:

  • NetBeans IDE 5.0 (download).
  • Java Standard Development Kit (JDK™) version 1.4.2 (download) or 5.0 (download)
  • JExcelApi — Java Excel library (download), version 2.5.9, but other versions should also work OK.

Notations Used in the Tutorial

  • <JEXCEL_HOME> - directory that contains your installation of JExcelApi library.

Tutorial Exercises

Exercise 1: Setting Up a Project with JExcelApi library

In this exercise you'll create NetBeans project and integrate it with installed Excel library.

Creating a ReadExcel Application Project

  1. Run NetBeans and choose File > New Project New Project wizards opens.
  2. Leave default selection (General/Java Application) and step to the next wizard page by clicking the Next button.
  3. Name the project ReadExcel and specify a location for your project or leave default one. Then click Finish. The project is created and its main class opened in the editor. Note that by default NetBeans automatically creates a package with the name of the project for you.

Adding the JExcelApi Library to the Project Classpath

The project is created and now it's time to configure NetBeans IDE to use the JExcelAPI library.

  1. Go to Tools > Library Manager and click New Library. The dialog for adding a new library is opened.
  2. Create a new library named JExcelApi and confirm by clicking OK. The JExcelApi library is added to the list of class libraries and now it's time to point NetBeans to the classes, sources, and API docs of the library.
  3. Click Add JAR/Folder and choose file jxl.jar, which is located in <JEXCEL_HOME> directory, confirm using the Add JAR/Folder button. The <JEXCEL_HOME>/jxl.jar file appears in the list of Library Classpath.
  4. Now go to the Sources tab, click Add JAR/Folder button, and add the <JEXCEL_HOME>/src folder. The <JEXCEL_HOME>/src folder appears in Library Sources list.
  5. Repeat the same procedure in the Javadoc tab, selecting the <JEXCEL_HOME>/docs folder.
  6. Configuration of added library is done, confirm by clicking OK button on the Library Manager dialog. Now we need to associate added Excel library with our ReadExcel project.
  7. Right click the ReadExcel project in Projects view and choose Properties. The Project Properties dialog opens.
  8. Select the Libraries node from the Categories tree on the left side of the dialog and click Add Library. The Compile tab lists the known libraries on your project's classpath.
  9. Click Add Library and select JExcelAPI library from the list. The JExcelApi library is displayed in Compile-time Libraries list.
  10. Finish the association by clicking OK.

Testing JExcelApi Library Integration

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:

  1. Go to editor, into opened Main.java source, method main (String[] args) body and write text Work and then click Ctrl+Space to invoke code completion. You should see that code completion is now offering you the Workbook java class, which belongs to the JExcelApi library, like in the follwing image.
  2. Select Workbook and press enter to complete the class name. Notice the IDE enters an import statement for the class as well. Then Ctrl key and click the class name in the editor (which turned into link). The source of Workbook.java is opened. This means you can jump to library code easily.
  3. Select the Workbook.java editor tab and press Alt+F1. The Javadoc documentation is opened in the browser.

Note that process of mapping specific library, described above, can be used generally to map any library with classes and/or sources.

Summary

You configured the JExcelApi library for use in NetBeans IDE and created a project which uses the library, making coding against the library easy.

Exercise 2: Designing and Coding ReadExcel Application

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.

Designing UI of ReadExcel Application

  1. Choose File > New File. Select the JFrame Form template from the Java GUI Forms category and click Next.
  2. Type ReadExcelUI as the class name, org.excelreader.ui as the package, and click Finish. The ReadExcelUI.java form is opened in the Form Designer.
  3. Choose JMenuBar from Palette and drop it anywhere in the form. The menu bar appears at the top of the form.
  4. Choose JTable from the Palette and drop it into the form, with the default spacing between the menu bar and the left edge of the form, as shown in the following figure.

    table being entered into the form.

  5. 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.

  6. Click on the Menu bar title in the frame and change its text to File.
  7. Now go to the Inspector view and select node in the tree which is called jMenu1 [JMenu] , right click it and choose Add > JMenuItem from to pop up menu.
  8. Right click jMenu1 [JMenu] again, Add > JSeparator, then Add > JMenuItem once more.
  9. Select jMenuItem1 [JMenuItem], go to the Properties view, find property Text and type Open.
  10. Repeat previous step with node jMenuItem2 [JMenuItem], change its text property to Exit.
  11. Now click the preview button icon in the Form Designer toolbar. The result of our UI design should look like following image:

    preview of the form

    The basic UI is done at this point and we can continue with finally coding some functionality for our UI shell.

Exercise 3: Adding Functionality to the UI

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.

Implementing Excel File Loading and Displaying

  1. In the Inspector window, right-click jMenuItem1 and choose Events > Action > actionPerformed to generate the action handler.
  2. In the generated jMenuItem1ActionPerformed method, we implement actual loading and displaying of Excel data with the following code. (The File object is java.io.File.)
        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());
  1. The methods of interest are especially readExcelSheet(File) and displaySheet(Sheet, Table). Here is the implementation of readExcelSheet, which gives an example of how to load Excel data from a file and includes simple error handling:
    /** 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);
    }
  1. The preferred way to display a loaded sheet is by following the Swing model-view-controller architecture. This means we will implement our own model for the JTable which will enable the display of data objects from JExcelApi in the JTable. Here is the implementation of the displaySheet method and the TableModel:
    /** 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.

Finalizing and Testing ReadExcel Application

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.

  1. Add code which uses JFileChooser to let the user specify an input file:
    /** 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";
        }
    }
  1. Switch back to the Design view of ReadExcelUI.java by clicking the Design button in the toolbar. Add an exit action handler - right-click the jMenuItem2 node in the Inspector window and choose Events > Action > actionPerformed to generate action handler. In generated jMenuItem2ActionPerformed method, implement a simple exit:
        dispose();
        System.exit(0);
  1. Import classes used in code we added in previous steps - choose Source > Fix Imports in main menu and and after the dialog is shown, choose to import javax.swing.filechooser.FileFilter and java.io.File. All red lines on the right side of the editor should vanish and file ReadExcelUI.java should be compilable without any errors at this point.
  2. Our application should be complete, so click Shift+F6 key shortcut (while ReadExcelUI.java is active) to actually run it.
  3. After application frame is shown, go to its menu File > Open. and find example Excel file, which is located in your JExcelApi installation, namely <JEXCEL_HOME>/jxlrwtest.xls and click Open.
  4. Excel file is loaded and shown in the table and should look like this:

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.

Summary

You just wrote and tested a simple application which reads and displays Excel *.xls spreadsheet files using NetBeans IDE and the JExcelApi library.

Next Steps

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE development features, join the mailing list.


↑返回目录
前一篇: How to Start with the Database Explorer
后一篇: Importing a 3rd Party Project as a NetBeans Free-Form Project