您好,登錄后才能下訂單哦!
學(xué)習(xí)excl操作
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 本類主要實現(xiàn)后綴為xlsx的 excel文件操作
*/
public class ExcelUtil {
private XSSFSheet ExcelWSheet; //excl單元格sheet頁面
private XSSFWorkbook ExcelWBook; //整個excl對象
private XSSFCell Cell; // 列對象
private XSSFRow Row;// 行對象
private String filePath; // 文件路徑
/** 構(gòu)造方法 */
// 設(shè)定要操作的 Excel 的文件路徑和 Excel 文件中的 sheet 名稱
// 在讀寫excel的時候,均需要先調(diào)用此方法,設(shè)定要操作的 excel 文件路徑和要操作的 sheet 名稱
public ExcelUtil(String Path, String SheetName) throws Exception {
FileInputStream ExcelFile;
try {
// 實例化 excel 文件的 FileInputStream 對象
ExcelFile = new FileInputStream(Path);
// 實例化 excel 文件的 XSSFWorkbook 對象
ExcelWBook = new XSSFWorkbook(ExcelFile); //整個文件
// 實例化 XSSFSheet 對象,指定 excel 文件中的 sheet 名稱,后續(xù)用于 sheet 中行、列和單元格的操作
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
this.filePath = Path;
}
// 讀取 excel 文件指定單元格的函數(shù),此函數(shù)只支持后綴為xlsx的 excel 文件
public String getCellData(int RowNum, int ColNum) throws Exception {
try {
// 通過函數(shù)參數(shù)指定單元格的行號和列號,獲取指定的單元格對象
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
// 如果單元格的內(nèi)容為字符串類型,則使用 getStringCellValue 方法獲取單元格的內(nèi)容
// 如果單元格的內(nèi)容為數(shù)字類型,則使用 getNumericCellValue() 方法獲取單元格的內(nèi)容
String CellData = "";
/** 獲取單元格類型 */
if (Cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { // 如果是字符串
CellData = Cell.getStringCellValue();
} else if (Cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { // 如果是數(shù)字
DecimalFormat df = new DecimalFormat("0");
CellData = df.format(Cell.getNumericCellValue());
}
return CellData;
} catch (Exception e) {
e.printStackTrace();
return ""; //如果異常返回空
}
}
/**在Excel文件的執(zhí)行單元格中寫輸入數(shù)據(jù),此函數(shù)只支持后綴為xlsx的文件寫入
* @param result 結(jié)果
* @param rowNum 行數(shù)
* @param cellNum 列數(shù)
* */
public void setCellData(int RowNum, int ColNum, String result) throws Exception {
try {
// 獲取 excel文件中的行對象
Row = ExcelWSheet.getRow(RowNum);
// 如果單元格為空,則返回 Null
Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
if (Cell == null ) {
// 當(dāng)單元格對象是 null 的時候,則創(chuàng)建單元格
// 如果單元格為空,無法直接調(diào)用單元格對象的 setCellValue 方法設(shè)定單元格的值
Cell = Row.createCell(ColNum);
// 創(chuàng)建單元格后可以調(diào)用單元格對象的 setCellValue 方法設(shè)定單元格的值
Cell.setCellValue(result);
} else {
// 單元格中有內(nèi)容,則可以直接調(diào)用單元格對象的 setCellValue 方法設(shè)定單元格的值
Cell.setCellValue(result);
System.out.println("執(zhí)行完成");
}
// 實例化寫入 excel 文件的文件輸出流對象
FileOutputStream fileOut = new FileOutputStream(filePath);
// 將內(nèi)容寫入 excel 文件中
ExcelWBook.write(fileOut);
// 調(diào)用flush 方法強制刷新寫入文件
fileOut.flush();
// 關(guān)閉文件輸出流對象
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
throw (e);
}
}
/**從 excel 文件獲取測試數(shù)據(jù)的靜態(tài)方法*/
public static Object[][] getTestData(String excelFilePath, String sheetName) throws IOException {
// 根據(jù)參數(shù)傳入的數(shù)據(jù)文件路徑和文件名稱,組合出 excel 數(shù)據(jù)文件的絕對路徑
// 聲明一個 file 文件對象
File file = new File(excelFilePath);
// 創(chuàng)建 FileInputStream 對象用于讀取 excel 文件
FileInputStream inputStream = new FileInputStream(file);
// 聲明 Workbook 對象
Workbook Workbook = null;
// 獲取文件名參數(shù)的后綴名,判斷是xlsx文件還是xls文件
String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf("."));
// 判斷文件類型如果是xlsx,則使用 XSSFWorkbook 對象進行實例化 2007
// 判斷文件類型如果是xls,則使用 SSFWorkbook 對象進行實例化 2003
if (fileExtensionName.equals(".xlsx")) {
Workbook = new XSSFWorkbook(inputStream);
} else if (fileExtensionName.equals(".xls")) {
Workbook = new HSSFWorkbook(inputStream);
}
// 通過 sheetName 參數(shù),生成 sheet 對象
Sheet Sheet = Workbook.getSheet(sheetName);
// 獲取 excel 數(shù)據(jù)文件中 sheet1中數(shù)據(jù)的行數(shù),getLastRowNum 方法獲取數(shù)據(jù)的最后行號
// getFirstRowNum 方法獲取數(shù)據(jù)的第一行行號,相減之后算出數(shù)據(jù)的行數(shù)
// 注意:excel 文件的行號和列號都是從 0 開始
int rowCount = Sheet.getLastRowNum() - Sheet.getFirstRowNum();
System.out.println(rowCount);
// 創(chuàng)建名為 records 的 list 對象來存儲從 excel數(shù)據(jù)文件讀取的數(shù)據(jù)
//
List<Object[]> records = new ArrayList<Object[]>();
// 使用 2 個 for 循環(huán)遍歷 excel 數(shù)據(jù)文件的所有數(shù)據(jù)(除了第一行,第一行是數(shù)據(jù)列名稱)
// 所以 i 從1開始,而不是從 0; 0表示表頭
for (int i = 1; i <= rowCount; i++) {
// 使用 getRow 方法獲取行對象
Row row = Sheet.getRow(i);
/*
* 聲明一個數(shù)組,來存儲 excel 數(shù)據(jù)文件每行中的測試用例和數(shù)據(jù),數(shù)組的大小用 getLastCellNum-1
* 來進行動態(tài)聲明,實現(xiàn)測試數(shù)據(jù)個數(shù)和數(shù)組大小相一致因為 excel 數(shù)據(jù)文件中
* 的測試數(shù)據(jù)行的最后一個單元格為測試執(zhí)行結(jié)果,倒數(shù)第二個單元格為此測試數(shù)據(jù)行
* 是否運行的狀態(tài)位,所最后兩列的單元格數(shù)據(jù)并不需要傳入到測試方法中,所以使用 getLastCellNum-2
* 的方式去掉每行中的最后兩個單元格數(shù)據(jù),計算出需要存儲的測試數(shù)據(jù)個數(shù),并 作為測試數(shù)據(jù)數(shù)組的初始化大小
*/
String fields[] = new String[row.getLastCellNum() - 2];//最后兩行不是要的所以去掉2 fielcls存放結(jié)果
/*
* if 用于判斷數(shù)據(jù)行是否要參與測試的執(zhí)行,excel 文件的倒數(shù)第二列為數(shù)據(jù)行的狀態(tài)位,標(biāo)記為 *
* "y"表示此數(shù)據(jù)行要被測試腳本執(zhí)行,標(biāo)記為非"y"的數(shù)據(jù)行均被認(rèn)為不會參與測試腳本的執(zhí)行,會 被跳過
*/
System.out.println(row.getCell(row.getLastCellNum() - 2).getStringCellValue());
if (row.getCell(row.getLastCellNum() - 2).getStringCellValue().equals("y")) { //y判斷是否之執(zhí)行。 equalsIgnoreCase
for (int j = 0; j < row.getLastCellNum() - 2; j++) {
// 判斷excel 的單元格字段是數(shù)字還是字符,字符串格式調(diào)用 getStringCellValue 方法獲取
// 數(shù)字格式調(diào)用 getNumericCellValue 方法獲取
if (row.getCell(j).getCellType() == XSSFCell.CELL_TYPE_STRING) { //字符串
fields[j] = row.getCell(j).getStringCellValue();
} else if (row.getCell(j).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
DecimalFormat df = new DecimalFormat("0");
fields[j] = df.format(row.getCell(j).getNumericCellValue());
} else {
System.out.println("格式錯誤");
}
}
// fields 的數(shù)據(jù)對象存儲到 records的 list 中
records.add(fields);
}
}
// 定義函數(shù)返回值,即 Object[][]
// 將存儲測試數(shù)據(jù)的 list 轉(zhuǎn)換為一個 Object 的二維數(shù)組
Object[][] results = new Object[records.size()][];
// 設(shè)置二維數(shù)組每行的值,每行是個object對象
for (int i = 0; i < records.size(); i++) {
results[i] = records.get(i);
}
// 關(guān)閉 excel 文件
return results;
}
public int getLastColumnNum() {
// 返回數(shù)據(jù)文件的最后一列的列號,如果有12列,則結(jié)果返回 11
return ExcelWSheet.getRow(0).getLastCellNum() - 1;
}
public static void main(String[] args) throws Exception
{
// ExcelUtil eu=new ExcelUtil("configs/test.xlsx", "Sheet1");
// eu.setCellData(2, 7, "執(zhí)行失敗"); // 寫入ok
// System.out.println(eu.getCellData(1, 2)); //讀取ok
//
System.out.println("讀取:");
Object[][] obd = getTestData("D:\\TOOL\\sysbj\\BjToon\\configs\\test.xlsx", "Sheet3");
for(int i =0 ; i < obd.length; i++)
{
Object[] obl = obd[i];
System.out.println("=============");
for(int j = 0; j < obl.length; j++)
{
System.out.println(obl[j]);
}
}
System.out.println("excle讀取成功:");
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。