poi讀取excel表格
阿新 • • 發佈:2018-12-05
import java.io.*; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook; 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.xssf.usermodel.XSSFWorkbook; /** * excel讀寫工具類 */ public class poioutput { private Workbook wb; private Sheet sheet; private Row row; public void ReadExcelUtils(String filepath) { if (filepath == null) { return; } String ext = filepath.substring(filepath.lastIndexOf(".")); try { InputStream is = new FileInputStream(filepath); if (".xls".equals(ext)) { wb = new HSSFWorkbook(is); } else if (".xlsx".equals(ext)) { wb = new XSSFWorkbook(is); } else { wb = null; } } catch (FileNotFoundException e) { } catch (IOException e) { } } /** * 讀取Excel表格表頭的內容 * @return String 表頭內容的陣列 */ public String[] readExcelTitle() throws Exception{ if(wb==null){ throw new Exception("Workbook物件為空!"); } sheet = wb.getSheetAt(0); row = sheet.getRow(0); // 標題總列數 int colNum = row.getPhysicalNumberOfCells(); String[] title = new String[colNum]; for (int i = 0; i < colNum; i++) { // title[i] = getStringCellValue(row.getCell((short) i)); title[i] = row.getCell(i).getStringCellValue(); } return title; } /** * 讀取Excel資料內容 * @return Map 包含單元格資料內容的Map物件 */ public void readExcelContent() throws Exception{ if(wb==null){ throw new Exception("Workbook物件為空!"); } sheet = wb.getSheetAt(0); // 得到總行數 int rowNum = sheet.getLastRowNum(); row = sheet.getRow(0); int colNum = row.getPhysicalNumberOfCells(); // 正文內容應該從第二行開始,第一行為表頭的標題 for (int i = 1; i <= rowNum; i++) { row = sheet.getRow(i); int j = 0; while (j < colNum) { System.out.print(row.getCell(j)+" "); j++; } System.out.println(""); } }
結果: