在Apache POI中实现VBA的Sheet.range()函数

时间:2018-03-12 16:45:03

标签: vba excel-vba apache-poi excel

所有

我对Apache POI很新,正如标题所说,我想根据Range()函数的API,或者可以一起工作来构建该函数的API,例如:

在VBA中:

Application.getSheets("Sheet1").Range("A2:F3")

在POI中,在我得到表单之后,我不确定实现该Range()的最佳方法是什么:

new WorkBook(/* excel file input stream*/).getSheet("Sheet1") // then what?

1 个答案:

答案 0 :(得分:2)

到目前为止VBA中只有Range apache poi。但是,使用什么取决于你需要对细胞范围做些什么。如果需要从" A2:F3"这样的字符串中获取Cell s。然后CellRangeAddress可能会有所帮助。

示例:

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();

 }
}

顺便说一下:整个Package org.apache.poi.ss.util值得关注。