NoClassDefFoundError:使用java处理excel表时出现UnsupportedFileFormatException

时间:2021-10-01 20:22:55

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.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.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$1.run(Unknown Source)
at java.net.URLClassLoader$1.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

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?

如何删除此错误?

3 个解决方案

#1


10  

This is covered in the Apache POI FAQ page:

这在Apache POI FAQ页面中有所介绍:

Can I mix POI jars from different versions?

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

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-3.11.jar和poi-ooxml-3.9.jar等组合,并且无法以不可预测的方式工作。

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

您将自己列为使用poi-3.9.jar和poi-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罐都来自同一版本。我建议你从下载页面(写作时为3.12)获取最新的POI版本,并使用一套一致的罐子

#2


0  

I tried the same and got the same error. It is because poi jars are duplicated in the pom.xml file.

我尝试了同样的错误。这是因为poi jar在pom.xml文件中是重复的。

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

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

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)'必须是唯一的:org.apache。 poi:poi:jar - >版本3.9 @第36行的重复声明,

#3


-1  

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.

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

#1


10  

This is covered in the Apache POI FAQ page:

这在Apache POI FAQ页面中有所介绍:

Can I mix POI jars from different versions?

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

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-3.11.jar和poi-ooxml-3.9.jar等组合,并且无法以不可预测的方式工作。

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

您将自己列为使用poi-3.9.jar和poi-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罐都来自同一版本。我建议你从下载页面(写作时为3.12)获取最新的POI版本,并使用一套一致的罐子

#2


0  

I tried the same and got the same error. It is because poi jars are duplicated in the pom.xml file.

我尝试了同样的错误。这是因为poi jar在pom.xml文件中是重复的。

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

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

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)'必须是唯一的:org.apache。 poi:poi:jar - >版本3.9 @第36行的重复声明,

#3


-1  

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.

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