【问题标题】:How to read data from Excel in JavaFX application?如何在 JavaFX 应用程序中从 Excel 中读取数据?
【发布时间】:2019-07-05 12:27:43
【问题描述】:

我正在创建一个 JavaFX FXMl 应用程序,其中 hibernate 作为 Java 中的 ORM。我想从 Excel 中读取数据并使用 hibernate 将其存储到 MySQL,但它无法创建 Workbook。

我花了几个小时阅读教程和其他帖子,无论是在 SO 还是其他网站,都没有接受的答案和 cmets 对我有帮助。

在我的Form_Main.fxml 文件中,我有一个按钮,可以调用相关方法从 Excel 中读取数据。我添加了以下 JAR 文件:
* poi-4.1.0
* poi-ooxml-4.1.0
* poi-ooxml-schemas-4.1.0
* xmlbeans-3.0.1
* commons-collections4-4.2
到项目。我读取数据的导入如下:

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;

我定义的方法是:

FileInputStream _File = new FileInputStream(new File("D:\\Students_Info.xlsx"));
XSSFWorkbook _Workbook = new XSSFWorkbook(_File);
XSSFSheet _Sheet = _Workbook.getSheetAt(0);
XSSFRow _Row;

其余代码将使用 hibernate 将数据写入 MySQL。但它不起作用。

当我调试我的程序时,一行:

XSSFWorkbook _Workbook = new XSSFWorkbook(_File);

它跳转到文件FXMLLoader.java at line:

catch (InvocationTargetException exception) {
     throw new RuntimeException(exception);
}

我的堆栈跟踪(如果我正确的话)是:

     [java] Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
     [java]     at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
     [java]     at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
     [java]     at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
     [java]     at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
     [java]     at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
     [java]     at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
     [java]     at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
     [java]     at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
     [java]     at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
     [java]     at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
     [java]     at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
     [java]     at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
     [java]     at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
     [java]     at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
     [java]     at javafx.event.Event.fireEvent(Event.java:198)
     [java]     at javafx.scene.Node.fireEvent(Node.java:8411)
     [java]     at javafx.scene.control.Button.fire(Button.java:185)
     [java]     at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
     [java]     at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
     [java]     at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
     [java]     at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
     [java]     at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
     [java]     at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
     [java]     at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
     [java]     at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
     [java]     at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
     [java]     at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
     [java]     at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
     [java]     at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
     [java]     at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
     [java]     at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
     [java]     at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
     [java]     at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
     [java]     at javafx.event.Event.fireEvent(Event.java:198)
     [java]     at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
     [java]     at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
     [java]     at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
     [java]     at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
     [java]     at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
     [java]     at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
     [java]     at java.security.AccessController.doPrivileged(Native Method)
     [java]     at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$358(GlassViewEventHandler.java:432)
     [java]     at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410)
     [java]     at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
     [java]     at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
     [java]     at com.sun.glass.ui.View.notifyMouse(View.java:937)
     [java]     at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
     [java]     at com.sun.glass.ui.win.WinApplication.lambda$null$152(WinApplication.java:177)
     [java]     at java.lang.Thread.run(Thread.java:748)
     [java] Caused by: java.lang.reflect.InvocationTargetException
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     [java]     at java.lang.reflect.Method.invoke(Method.java:498)
     [java]     at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
     [java]     at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
     [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     [java]     at java.lang.reflect.Method.invoke(Method.java:498)
     [java]     at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
     [java]     at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
     [java]     ... 48 more
     [java] Caused by: java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap
     [java]     at school_system.Model.TblStudent.importDataFromFile(TblStudent.java:107)
     [java]     at school_system.Controllers.Controller_Main.handleImportDataButtonAction(Controller_Main.java:34)
     [java]     ... 58 more
     [java] Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.ListValuedMap
     [java]     at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
     [java]     at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
     [java]     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
     [java]     at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
     [java]     ... 60 more

【问题讨论】:

  • 我猜你对 xlsx 文件类型使用了错误的导入。
  • @AxelRichter,我已经更正了我的 JAR 文件版本。全部来自 poi-4.1.0 zip 文件。但问题依然存在。
  • @Sedrick Documents 说,对于 Excel 2007 及更高版本,我必须使用 XSSF 导入。
  • 另外,花点时间学习 Java 命名约定。这在使用 JavaFX 编写代码时非常重要。
  • 根本问题是Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.ListValuedMap。根据包名称,您似乎缺少 Apache Commons Collections 依赖项,这可能是 Apache POI 的传递依赖项。你是如何处理依赖管理的?马文?摇篮?

标签: java excel javafx apache-poi fxml


【解决方案1】:

这是我创建的用于读取EXCEL 文件的实用程序。希望它可以帮助你。 Main 方法仅用于测试目的,可以删除。

代码使用

List<List<String>> excelData = ExcelFileUtility.readExcelFile("fileName.xlsx");

完整代码:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Cell;
import static org.apache.poi.ss.usermodel.CellType.BLANK;
import static org.apache.poi.ss.usermodel.CellType.BOOLEAN;
import static org.apache.poi.ss.usermodel.CellType.FORMULA;
import static org.apache.poi.ss.usermodel.CellType.NUMERIC;
import static org.apache.poi.ss.usermodel.CellType.STRING;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
 *
 * @author blj0011
 */
public class ExcelFileUtility
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        readExcelFileWithHeaderFirstRow("Copy of Database_Details_Report_AAA.xlsx", false).forEach((t) -> {
            t.forEach((z) -> {
                System.out.print(z + " - ");
            });

            System.out.println();
        });
    }

    public static List<List<String>> readExcelFile(String fileName)
    {
        List<List<String>> excelContent = new ArrayList();
        int columnCounter = 0;
        int rowCounter = 0;

        try (InputStream inputStream = new FileInputStream(fileName)) {
            DataFormatter formatter = new DataFormatter();

            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                List<String> tempList = new ArrayList();

                for (Cell cell : row) {
                    String text = formatter.formatCellValue(cell);
                    System.out.print(++columnCounter + ": " + text);
                    System.out.println(text.length());
                    tempList.add(text);
                }
                columnCounter = 0;
                excelContent.add(tempList);

                ++rowCounter;
                //Used for testing
                //if (rowCounter == 5) {
                //    break;
                //}
                //System.out.println(String.join(" - ", tempList));
                //System.out.println(tempList.size());

            }
        }
        catch (IOException | EncryptedDocumentException ex) {
            System.out.println(ex.toString());
        }

        return excelContent;
    }

    public static List<List<String>> readExcelFileWithHeaderFirstRow(String fileName, boolean allCellHaveData)
    {
        List<List<String>> sheetData = new ArrayList();
        int headerCount = 0;

        try (FileInputStream fis = new FileInputStream(fileName);
             Workbook wb = WorkbookFactory.create(fis)) {

            Sheet sheet = wb.getSheetAt(0);
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
                Row row = sheet.getRow(i);
                String value;

                List<String> rowData = new ArrayList();
                //System.out.println("\nROW " + row.getRowNum() + " has " + row.getPhysicalNumberOfCells() + " cell(s).");
                //System.out.println("last cell number: " + row.getLastCellNum());
                if (i == 0) {
                    headerCount = row.getLastCellNum();
                }

                for (int c = 0; c < row.getLastCellNum(); c++) {

                    Cell cell = row.getCell(c);

                    if (cell != null) {
                        switch (cell.getCellType()) {
                            case FORMULA:
                                value = "FORMULA value=" + cell.getCellFormula();
                                rowData.add(cell.getCellFormula());
                                break;

                            case NUMERIC:
                                value = "NUMERIC value=" + cell.getNumericCellValue();
                                rowData.add(Double.toString(cell.getNumericCellValue()));
                                break;

                            case STRING:
                                value = "STRING value=" + cell.getStringCellValue();
                                rowData.add(cell.getStringCellValue());
                                break;

                            case BLANK:
                                value = "<BLANK>";
                                rowData.add("");
                                break;

                            case BOOLEAN:
                                value = "BOOLEAN value-" + cell.getBooleanCellValue();
                                rowData.add(cell.getBooleanCellValue() ? "true" : "false");
                                break;

                            case ERROR:
                                value = "ERROR value=" + cell.getErrorCellValue();
                                rowData.add(Byte.toString(cell.getErrorCellValue()));
                                break;

                            default:
                                value = "UNKNOWN value of type " + cell.getCellType();
                                rowData.add(cell.getCellType().toString());
                        }
                        //System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" + value);
                    }
                    else {
                        //System.out.println("CELL col=" + " VALUE=" + "<My Blank>");
                        rowData.add("<My Blank>");
                    }
                }

                if (!allCellHaveData) {
                    int currentRowCount = row.getLastCellNum();
                    while (currentRowCount < headerCount) {
                        rowData.add("<Blank end column>");
                        currentRowCount++;
                    }
                }
                sheetData.add(rowData);
            }
        }
        catch (FileNotFoundException ex) {
            System.out.println(ex);
        }
        catch (IOException ex) {
            System.out.println(ex);
        }

        return sheetData;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2016-12-19
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多