close
※怕自己忘記特別做個簡單的操作紀錄※
由於分析數據會用到很多excel的檔案,故使用POI這個開源碼來進行excel的讀取及資料的抓取。
POI我覺得目前主要分為四個部分
Workbook(Excel本體)、Sheet(內部頁面)、Row(頁面之行(橫的))、Cell(行內的元素)
POI的起始值也為0,故第一頁為0、第二頁為1...以此類推。
//利用FileInputStream讀取該路徑之檔案,".\\"為根目錄之意思 FileInputStream inp = new FileInputStream(".\\workbookwc.xlsx"); //利用wb承接FileInputStream所讀取的檔案 XSSFWorkbook wb = new XSSFWorkbook(inp); XSSFSheet sheet = wb.getSheetAt(0);//讀取wb內的頁面 XSSFRow row = sheet.getRow(2);//讀取頁面0的第二行 XSSFCell cell = row.getCell(3);//讀取第二行的第三個元素 System.out.println(cell);//可直接透過println輸出cell
以下是透過迴圈掃描Excel中某個整張頁面
public static void scaneWholeFile(String file) throws FileNotFoundException, IOException {
//1.Read Excel File into workbook
FileInputStream inp = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(inp);
inp.close();
//2.get wb sheet(0)
XSSFSheet sheet = wb.getSheetAt(0);
//get total num of row
int rowLength = sheet.getLastRowNum();
String sheetName = sheet.getSheetName();
System.out.println(sheetName);
//3.get wb row
XSSFRow row = sheet.getRow(0);
//total num of cols(cell)
int cellLength = row.getLastCellNum();
//4.get wb cols(cell
XSSFCell cell = row.getCell(0);
//this loop will scane all info at each cell
for (int i = 0; i <= rowLength; i++) {
//get each row
XSSFRow row1 = sheet.getRow(i);
for (int j = 0; j < cellLength; j++) {
//get each cols
XSSFCell cell1 = row1.getCell(j);
System.out.print(cell1 + " ");
}
System.out.println();
}
}
refference: https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFWorkbook.html
全站熱搜