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();
}
}
}
原文地址:https://www.cnblogs.com/xixi0203/p/10178579.html
时间: 2024-10-17 08:03:44