package logpost;
import java.io.File;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelUtil {
/***
* 1.獲取workbook對象
* 2.獲取sheet對象
* 3.獲取行
* 4.獲取列
* @return
*/
public static Object[][] name(String excelPath,int startRow,int endRow,int startCell,int endCell) {
//String excelPath="E:\\InterfaceAuto\\LogCase.xls";
Object[][]datas=new Object[endRow-startRow+1][endCell-startCell+1];
// 1.獲取workbook對象
//File file=new File(excelPath);
try {
Workbook workbook=WorkbookFactory.create(new File(excelPath));
// 2.獲取sheet對象
Sheet sheet=workbook.getSheet("log");
// 3.獲取行
// 4.獲取列
for(int i=startRow-1;i<endRow;i++) {
Row row=sheet.getRow(i);
for (int j = startCell-1; j < endCell; j++) {
Cell cell=row.getCell(j);
//將列設置字符串形式
cell.setCellType(org.apache.poi.ss.usermodel.CellType.STRING);
String value=cell.getStringCellValue();
System.out.println("---------------");
System.out.println("value:"+value);
datas[i-1][j-5]=value;
}
}
//
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return datas;
}
public static void main(String[]args) {
String excelPath="src/test/resources/LogCase1.xls";
Object[][]datas=name(excelPath,2,4,6,7);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("["+datas[i][j]+"]"+"\n");
}
}
}
}
讀取結果: