使用POI对excel进行操作生成二维数组

Posted xixi0203

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用POI对excel进行操作生成二维数组相关的知识,希望对你有一定的参考价值。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Pois {

  static Logger logger = LoggerFactory.getLogger(Pois.class);
  static Workbook workbook = new HSSFWorkbook();
  static String rootPath = System.getProperty("user.dir");
  
  //生成二维数组
  public static Object[][] readTestData(String workBookName, String sheetName) {
    readTestDataFromWorkBook(workBookName);
    Sheet sheet = workbook.getSheet(sheetName);
    int lastRowNum = sheet.getLastRowNum();
    short lastCellNum = sheet.getRow(0).getLastCellNum();
    int cellNUm = lastCellNum - 2;
    Object[][] objects = new Object[lastRowNum][cellNUm];
    for (int i = 0; i < lastRowNum; i++) {
      for (int j = 0; j < cellNUm; j++) {
        Cell cell = sheet.getRow(i + 1).getCell(j);
        if (cell.getCellTypeEnum().equals(CellType.STRING)) {
          objects[i][j] = cell.getStringCellValue();
        }
        if (cell.getCellTypeEnum().equals(CellType.NUMERIC)) {
          objects[i][j] = cell.getNumericCellValue();
        }
      }
    }
    closeBook();
    return objects;
  }

  //从workbook中读取数据
  private static void readTestDataFromWorkBook(String workBookName){
    File file = new File(rootPath + "/src/test/resources/" + workBookName);
    try {
      InputStream inputStream = new FileInputStream(file);
      workbook = WorkbookFactory.create(inputStream);
      inputStream.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (InvalidFormatException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  //关闭workbook
  private static void closeBook(){
    try {
      workbook.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

以上是关于使用POI对excel进行操作生成二维数组的主要内容,如果未能解决你的问题,请参考以下文章

Java使用POI插件将数据以excel形式备份

Java使用 POI 操作Excel

POI动态生成Excel

java--Excel操作工具——POI

java利用poi读取Excel文件

POI对Excel进行读取操作,工具类,便于操作数据