To iterate over rows and cells of an Excel file in Java, you can use a library like Apache POI. Apache POI provides a powerful set of Java libraries for reading and writing Microsoft Office file formats, including Excel.
Here's an example of how you can iterate over rows and cells of an Excel file using Apache POI in Java:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelIteratorExample {
public static void main(String[] args) {
String filePath = "path/to/your/excel/file.xlsx";
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0); // Assuming the first sheet
// Iterate over rows
for (Row row : sheet) {
// Iterate over cells
for (Cell cell : row) {
CellValue cellValue = evaluateCell(cell);
System.out.print(cellValue + "\t");
}
System.out.println(); // Move to the next line after each row
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Evaluate cell value based on its type
private static CellValue evaluateCell(Cell cell) {
FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
return evaluator.evaluate(cell);
}
}
Make sure to replace "path/to/your/excel/file.xlsx" with the actual path to your Excel file. In this example, we use the XSSFWorkbook class to read the Excel file.
We open the file using FileInputStream, create an instance of XSSFWorkbook, and obtain the first sheet using getSheetAt(0). We then iterate over each row using a for-each loop and iterate over each cell within the row.
The evaluateCell method is used to evaluate the value of each cell, considering its type (e.g., numeric, string, formula).
Finally, we print the cell values, separating them with tabs, and move to the next line after each row. Remember to include the Apache POI dependencies in your project's classpath for this code to work.
No comments:
Post a Comment