All:
I am pretty new to Apache POI, as the title said, I want to find according API of that Range() function, or APIs that can work together to build that function, for example:
In VBA:
Application.getSheets("Sheet1").Range("A2:F3")
In POI, after I get the sheet, I am not sure what is best way to implement that Range():
new WorkBook(/* excel file input stream*/).getSheet("Sheet1") // then what?
There is nothing like VBA
Range
in apache poi
until now. But what to use instead depends on what exactly you needs to do with the range of cells. If the need is getting the Cell
s from a string like "A2:F3". Then CellRangeAddress may be of a help.
Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.FileInputStream;
class ExcelCellRange {
public static void main(String[] args) throws Exception {
DataFormatter formatter = new DataFormatter();
Workbook workbook = WorkbookFactory.create(new FileInputStream("file.xlsx"));
//Workbook workbook = WorkbookFactory.create(new FileInputStream("file.xls"));
Sheet sheet = workbook.getSheetAt(0);
System.out.println("This is sheet: " + sheet.getSheetName());
CellRangeAddress cellRangeAddress = CellRangeAddress.valueOf("D1:G8");
int firstRow = cellRangeAddress.getFirstRow();
int lastRow = cellRangeAddress.getLastRow();
int firstColumn = cellRangeAddress.getFirstColumn();
int lastColumn = cellRangeAddress.getLastColumn();
for (int r = firstRow; r <= lastRow; r++) {
for (int c = firstColumn; c <= lastColumn; c++) {
Row row = sheet.getRow(r);
if (row == null) {
System.out.println(new CellAddress(r, c) + " is in totally empty row.");
} else {
Cell cell = row.getCell(c);
String content = formatter.formatCellValue(cell);
System.out.println(new CellAddress(r, c) + " contains " + content);
}
}
}
workbook.close();
}
}
Btw.: The whole Package org.apache.poi.ss.util is worth attention.