I'm trying to create a file in Java. I have downloaded the lastest Apache POI version and kinda having troubles with all the "build path" thing. I'm not sure if I was doing everything right and not sure what jar files i should use. I try to run the code and thats the error I get:
Error: Unable to initialize main class TestCaused by: java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
My code:
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();
}
}
Maybe I have a problem with the classpath? How can I change it? If that's not the problem, Does anyone have an idea?
firstly be sure that you are using the latest version of this library in case you are using maven these dependencies helping you
<!-- 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>
also you have to create a file with .xls or .xlsx extensions you can use something like this
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");
Probably, you forgot to add some jar files in the classpath. Try to follow these steps:
Now it should work!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.