內容簡介
本文主要介紹使用POI進行Excel文件的相關操作,涉及讀取文件,獲取sheet表格,對單元格內容進行讀寫操作,以及合並單元格的操作。
Excel文件目錄
Excel模板文件存了resourse目錄下,如下圖:
POM引用
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency>
重要說明
如果是xls格式,使用HSSFWorkbook,HSSFSheet,HSSFRow來進行相關操作
如果是xlsx格式,使用XSSFWorkbook,XSSFSheet,XSSFRow來進行相關操作
讀取Excel文件
// 定義一個數據格式化對象 XSSFWorkbook wb = null; try { //excel模板路徑 File cfgFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/ExcelTemplate/ContradictionMatrix.xlsx"); InputStream in = new FileInputStream(cfgFile); //讀取excel模板 wb = new XSSFWorkbook(in); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
獲取sheet表格及讀寫單元格內容
//獲取sheet表格,及讀取單元格內容 XSSFSheet sheet = null; try{ sheet = wb.getSheetAt(0); //先將獲取的單元格設置為String類型,下面使用getStringCellValue獲取單元格內容 //如果不設置為String類型,如果單元格是數字,則報如下異常 //java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell sheet.getRow(2).getCell(2).setCellType(CellType.STRING); //讀取單元格內容 String cellValue = sheet.getRow(2).getCell(2).getStringCellValue(); //添加一行 XSSFRow row = sheet.createRow(1); //第2行開始寫數據 row.setHeight((short)400); //設置行高 //向單元格寫數據 row.createCell(1).setCellValue("名稱"); } catch (Exception e){ e.printStackTrace(); }
合並單元格
使用下面的語句合並單元格:
sheet.addMergedRegion(new CellRangeAddress(0,2,15,18));
看一下CellRangeAddress的構造函數:
/** * Creates new cell range. Indexes are zero-based. * * @param firstRow Index of first row * @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow} * @param firstCol Index of first column * @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol} */ public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) { super(firstRow, lastRow, firstCol, lastCol); if (lastRow < firstRow || lastCol < firstCol) throw new IllegalArgumentException("lastRow < firstRow || lastCol < firstCol"); }