使用POI操作XSSFWorkbook wb0 = new XSSFWorkbook();报错java.lang.NoClassDefFoundError

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

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

public class Test {
    public static void main(String[] args) throws IOException {
        FileOutputStream fout = new FileOutputStream("D:/标题内容.xlsx");
        XSSFWorkbook wb0 = new XSSFWorkbook();
        XSSFSheet sheet0 = wb0.createSheet("列表");
        XSSFRow firstRow = sheet0.createRow(0);
        XSSFCell[] cells = new XSSFCell[6];
        String[] titles = new String[]{"1", "2", "3", "4", "5", "6"};
        for (int i = 0; i < 6; i++) {
            cells[0] = firstRow.createCell(i);
            cells[0].setCellValue(titles[i]);
        }
    }
}


img

java中创建excel可以试下用spire.xls for java或其免费版,运行环境不依赖Microsoft Office。代码参考:

import com.spire.xls.*;

import java.awt.*;

public class CreateExcel {
    public static void main(String[] args){
        //创建Workbook实例 
        Workbook workbook = new Workbook();

        //获取第一张工作表(新建的Workbook默认包含3张工作表)
        Worksheet sheet = workbook.getWorksheets().get(0);
        //为第一张工作表设置名称
        sheet.setName("Data Sheet");

        //创建列头单元格样式
        CellStyle style1 = workbook.getStyles().addStyle("Header Style");
        style1.getFont().setSize(12f);
        style1.getFont().setColor(Color.BLACK);
        style1.getFont().isBold(true);
        style1.setHorizontalAlignment(HorizontalAlignType.Center);
        style1.setVerticalAlignment(VerticalAlignType.Center);

        //创建数据单元格样式
        CellStyle style2 = workbook.getStyles().addStyle("Data Style");
        style2.getFont().setSize(10f);
        style2.getFont().setColor(Color.BLACK);

        //为列头单元格添加数据并应用样式
        for (int column=1; column<5; column++)
        {
            CellRange header =sheet.getCellRange(1,column);
            header.setValue("Column " + column );
            header.setStyle(style1);
            header.setColumnWidth(15f);
        }

        //为数据单元格添加数据并应用样式
        for (int row=2; row<11; row++)
        {
            for (int column=1; column<5; column++)
            {
                CellRange cell = sheet.getCellRange(row, column);
                cell.setValue("Data " + row + ", " + column);
                cell.setStyle(style2);
            }
        }

        //保存结果文件
        workbook.saveToFile("CreateExcel.xlsx", FileFormat.Version2013);
    }
}