org.apache.poi中的异常

时间:2019-12-26 06:50:44

标签: java excel apache-poi

我试图编写一个可以读写.xlsx文件的程序,下面提供的代码旨在编写第一个excel程序。

package excel_reader;

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelWriter{

    public static void main(String[] args) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        // first sheet create
        HSSFSheet sheet = workbook.createSheet("FirstExcelSheet");
        // first row create - 1
        HSSFRow row = sheet.createRow(0);
        // first cell create - 1
        HSSFCell cell = row.createCell(0); // A-1
        // give data into A-1 cell
        cell.setCellValue("Tester");

        // Output as an excel file
        workbook.write(new FileOutputStream("D:\\book1.xlsx"));
        workbook.close();
    }
}

以某种方式,它无法在我提供的Excel工作表上书写,请帮帮我!

错误代码:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/math3/util/ArithmeticUtils
        at org.apache.poi.poifs.property.RootProperty.setSize(RootProperty.java:59)
        at org.apache.poi.poifs.property.DirectoryProperty.<init>(DirectoryProperty.java:52)
        at org.apache.poi.poifs.property.RootProperty.<init>(RootProperty.java:31)
        at org.apache.poi.poifs.property.PropertyTable.<init>(PropertyTable.java:58)
        at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:102)
        at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:124)
        at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1373)
        at excel_reader.ExcelWriter.main(ExcelWriter.java:25)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.math3.util.ArithmeticUtils
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        ... 8 more

1 个答案:

答案 0 :(得分:2)

通常, java.lang.NoClassDefFoundError:会在您缺少所需的jar时显示 检查是否在构建路径中添加了 commons-math3 jar,如果没有,请添加下载或使用maven依赖项。

如果您的项目是Maven项目,则将此依赖项添加到pom.xml中

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.0</version>
</dependency>