NoClassDefFoundError: UnsupportedFileFormatException 使用 java 处理 Excel 表时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30183250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:17:18  来源:igfitidea点击:

NoClassDefFoundError: UnsupportedFileFormatException while working with excel sheet using java

javaexcelapache-poixlsxxssf

提问by Gaurav Mahawar

I'm writing a Java program which reads from a .xlsx file and give the output in .csv format. This is my code:

我正在编写一个 Java 程序,它从 .xlsx 文件中读取并以 .csv 格式提供输出。这是我的代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat; 
import java.util.Date;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;   
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;

public class xlsxToCsv {

    public static void main(String[] args) {

        long startTime = System.currentTimeMillis();

        File inputFile = new File("C:\inputFile.xlsx");
        File outputFile = new File("C:\outputFile.csv");

        xlsx(inputFile, outputFile);

        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;

        System.out.println(elapsedTime);

   }

   private static void xlsx(File inputFile, File outputFile) {

        //for storing data into CSV files
        StringBuffer data = new StringBuffer();

        try {

            Writer w = new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8");

            // Get the workbook object for XLS file
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(inputFile));

            // Get first sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);
            Cell cell;
            Row row;

            // Iterate through each rows from first sheet
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) 
            {
                row = rowIterator.next();
                // For each row, iterate through each columns
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) 
                {
                    cell = cellIterator.next();

                    switch (cell.getCellType()) 
                    {
                        case Cell.CELL_TYPE_BOOLEAN:
                            data.append(cell.getBooleanCellValue() + ",");
                            break;

                        case Cell.CELL_TYPE_NUMERIC:
                            if(DateUtil.isCellDateFormatted(cell)) {
                                Date date = cell.getDateCellValue();
                                System.out.println(date.toString());
                                SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                                String d = sdf.format(date);
                                System.out.println(d);
                                data.append(d + ",");   
                            }
                            else if(cell.getNumericCellValue() == (int)cell.getNumericCellValue())
                                data.append((int)cell.getNumericCellValue() + ",");
                            else if(cell.getNumericCellValue() == (long)cell.getNumericCellValue())
                                data.append((long)cell.getNumericCellValue() + ",");
                            else
                                data.append(cell.getNumericCellValue() + ",");
                            break;

                        case Cell.CELL_TYPE_STRING:
                                data.append((cell.getStringCellValue()) + ",");
                                break;

                        case Cell.CELL_TYPE_BLANK:
                                data.append("" + ",");
                                break;

                        default:
                                data.append(cell + ",");
                        }

                        //data.append('\n'); 
                }
                data.append("\r\n");
        }

        w.write(data.toString());
        w.close();

    } catch(FileNotFoundException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

}

}

However, I'm getting the following error:

但是,我收到以下错误:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access0(Unknown Source)
at java.net.URLClassLoader.run(Unknown Source)
at java.net.URLClassLoader.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at xlsxToCsv.xlsxToCsv.xlsx(xlsxToCsv.java:47)
at xlsxToCsv.xlsxToCsv.main(xlsxToCsv.java:28)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.UnsupportedFileFormatException
at java.net.URLClassLoader.run(Unknown Source)
at java.net.URLClassLoader.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 14 more

I have included the following jars:

我已经包含了以下罐子:

  • dom4j-1.6.jar
  • poi-3.9.jar
  • poi-ooxml-3.11.jar
  • poi-ooxml-schemas-3.8-20120326.jar
  • xmlbeans-2.3.0.jar
  • dom4j-1.6.jar
  • poi-3.9.jar
  • poi-ooxml-3.11.jar
  • poi-ooxml-schemas-3.8-20120326.jar
  • xmlbeans-2.3.0.jar

I've checked the file format is .xlsx and also the directory but I don't understand what the problem is.

我检查了文件格式是 .xlsx 和目录,但我不明白问题是什么。

How can I remove this error?

我怎样才能消除这个错误?

采纳答案by Gagravarr

This is covered in the Apache POI FAQ page:

这在Apache POI 常见问题页面中有介绍

Can I mix POI jars from different versions?

No. This is not supported.

All POI jars in use must come from the same version. A combination such as poi-3.11.jar and poi-ooxml-3.9.jar is not supported, and will fail to work in unpredictable ways.

我可以混合不同版本的 POI 罐子吗?

不,这不受支持。

使用的所有 POI jar 必须来自同一版本。不支持 poi-3.11.jar 和 poi-ooxml-3.9.jar 等组合,并且会以不可预测的方式无法工作。

You list yourself as using poi-3.9.jarand poi-ooxml-3.11.jarwhich are from different versions, and won't work.

您将自己列为 usingpoi-3.9.jarpoi-ooxml-3.11.jar来自不同版本的,并且不起作用。

You need to ensure that all your POI jars come from the same version. I'd suggest you grab the latest POI release from the download page(3.12 as of writing), and use a consistent set of jars from that

您需要确保所有 POI jar 都来自同一版本。我建议您从下载页面(撰写本文时为 3.12)获取最新的 POI 版本,并使用一组一致的 jar

回答by Moosa

NoClassDefFoundError comes when JVM is unable to found library at run time. May be you added library in file path but it is not available at run time.

NoClassDefFoundError 当 JVM 在运行时无法找到库时出现。可能是您在文件路径中添加了库,但它在运行时不可用。

回答by Divya C

I tried the same and got the same error. It is because poijars are duplicated in the pom.xmlfile.

我尝试了同样的方法并得到了同样的错误。这是因为poijars 在pom.xml文件中重复。

I got these warnings which I ignored first. Later I tried removing duplicate poijars in pom.xml, which resolved the issue.

我首先忽略了这些警告。后来我尝试删除 中重复的poi罐子pom.xml,解决了这个问题。

This is the warning I got before:

这是我之前收到的警告:

[WARNING] Some problems were encountered while building the effective model for MavenProj:Perfumania:jar:0.0.1-SNAPSHOT [WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.apache.poi:poi:jar -> duplicate declaration of version 3.9 @ line 36,

[警告] 为MavenProj 构建有效模型时遇到一些问题:Perfumania:jar:0.0.1-SNAPSHOT [警告] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.apache。 poi:poi:jar -> 3.9 版@第 36 行的重复声明,

回答by raghuram

The reason is versions of poi,poi-ooxml,poi-ooxml-schemas should be same for example version should be 3.6 in you rpom.xml file

原因是 poi,poi-ooxml,poi-ooxml-schemas 的版本应该是相同的,例如在你的 rpom.xml 文件中版本应该是 3.6