Implementing VBA's Sheet.range() function in Apache POI

◇◆丶佛笑我妖孽 提交于 2019-12-24 18:43:44

问题


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?

回答1:


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 Cells 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.



来源:https://stackoverflow.com/questions/49240401/implementing-vbas-sheet-range-function-in-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!