[英]write to excel in java with Java Excel library -can't open file
[英]Can't Create an excel file (Java)
我正在尝试用Java创建文件。 我已经下载了最新的Apache POI版本,并且在所有“构建路径”方面都遇到了麻烦。 我不确定我是否做对了所有事情,也不确定应该使用哪些jar文件。 我尝试运行代码,多数民众赞成在我得到的错误:
错误:无法初始化主类Test。原因: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();
}
}
也许我的类路径有问题? 我该如何更改? 如果这不是问题,那么有人有想法吗?
首先,请确保您正在使用该库的最新版本,以防您使用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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.