我正在尝试用Java创建文件。我已经下载了最新的Apache POI版本,并且在所有“构建路径”方面都遇到了麻烦。我不确定我是否做对了所有事情,也不确定应该使用哪些jar文件。 我尝试运行代码,多数民众赞成在我得到的错误:
错误:无法初始化主类TestCaused由:java.lang.NoClassDefFoundError:org / apache / poi / ss / usermodel / Workbook
我的代码:
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
Workbook workbook = new XSSFWorkbook("Test.xlsx");
Sheet sheet = workbook.createSheet("SheetTest");
Row headerRow = sheet.createRow(0);
for (int i = 0; i < 5; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(i);
}
workbook.close();
}
}
也许我的类路径有问题?我该如何更改? 如果那不是问题,有人有想法吗?
答案 0 :(得分:0)
首先请确保您正在使用该库的最新版本 如果您使用的是maven,则这些依赖关系可以帮助您
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
还必须创建一个扩展名为.xls或.xlsx的文件 您可以使用类似
Workbook workbook = WorkbookFactory.create(new File(fileName));
Sheet sheet = workbook.createSheet("sheetName");
int rowIndex = 0;
// this is an example from the official site iterate over the list and fill the sheet
while(iterator.hasNext()){
Country country = iterator.next();
Row row = sheet.createRow(rowIndex++);
Cell cell0 = row.createCell(0);
cell0.setCellValue(country.getName());
Cell cell1 = row.createCell(1);
cell1.setCellValue(country.getShortCode());
}
//lets write the excel data to file now
FileOutputStream fos = new FileOutputStream(fileName);
workbook.write(fos);
fos.close();
System.out.println(fileName + " written successfully");
答案 1 :(得分:0)