Spring Boot 操作 Excel


Excel 在日常操作中經常使用到,Spring Boot 中使用 POI 操作 Excel

本項目源碼 github 下載

1 新建 Spring Boot Maven 示例工程項目

注意:本示例是用 IDEA 開發工具

  1. File > New > Project,如下圖選擇 Spring Initializr 然后點擊 【Next】下一步
  2. 填寫 GroupId(包名)、Artifact(項目名) 即可。點擊 下一步
    groupId=com.fishpro
    artifactId=excel
  3. 選擇依賴 Spring Web Starter 前面打鈎。
  4. 項目名設置為 spring-boot-study-excel.

文件上傳不需要引入第三方組件。

2 依賴引入 Pom.xml

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3 操作 Excel

不同的 Excel 版本具有不同的類來操作本示例中使用 xls 后綴版本。詳細請參見 官方文檔

3.1 創建 Workbook

  • HSSFWorkbook 是操作 Excel2003 以前(包括2003)的版本,擴展名是.xls;
  • XSSFWorkbook 是操作 Excel2007 后的版本,擴展名是.xlsx;
  • SXSSFWorkbook 是操作 Excel2007 后的版本,擴展名是.xlsx;
    public static void CreateNewWorkbook() {
        Workbook wb = new HSSFWorkbook();
        try {
            OutputStream fileOut = new FileOutputStream("workbook.xls");
            wb.write(fileOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Workbook wb2 = new XSSFWorkbook();
        try (OutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
            wb2.write(fileOut);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

3.2 創建工作表 Sheet

  • 工作表名稱不要超過 31 個字符
  • 名稱不能含有特殊字符
  • 可以使用 WorkbookUtil.createSafeSheetName 來創建安全的工作表名稱
public static void CreateNewSheet() {
        Workbook wb = new HSSFWorkbook();  // or new XSSFWorkbook();
        Sheet sheet1 = wb.createSheet("new sheet");
        Sheet sheet2 = wb.createSheet("new second sheet");
        String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]"); // returns " O'Brien's sales   "
        Sheet sheet3 = wb.createSheet(safeName);
        try {
            OutputStream fileOut = new FileOutputStream("workbook.xls");
            wb.write(fileOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3.3 創建單元格 Cells

  • 先有行在有列,先要創建 Row 在創建 Cell
  • 創建一個樣式
  • 創建一個日期類型的值
  • 創建日期、小數、字符 、布爾等類型
  • 創建一個邊框類型單元格
  • 數據格式化單元格
 /**
     *## 3.3 創建單元格 Cells
     * - 先有行在有列,先要創建 Row 在創建 Cell
     * */
    public void CreateNewCell() {
        Workbook wb = new HSSFWorkbook();  // or new XSSFWorkbook();
        Sheet sheet1 = wb.createSheet("new sheet");
        //先行后列
        Row row = sheet1.createRow(0);

        //創建列
        Cell cell = row.createCell(0);
        cell.setCellValue(new Date());
        //創建一個列的樣式
        CellStyle cellStyle = wb.createCellStyle();
        //獲取一個幫助類設置樣式
        CreationHelper createHelper = wb.getCreationHelper();
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
        cell = row.createCell(1);
        cell.setCellValue(new Date());
        cell.setCellStyle(cellStyle);
        //使用 Calendar
        cell = row.createCell(2);
        cell.setCellValue(Calendar.getInstance());
        cell.setCellStyle(cellStyle);
        //創建不同的類型的單元格
        row.createCell(3).setCellValue(1.1);
        row.createCell(4).setCellValue(new Date());
        row.createCell(5).setCellValue(Calendar.getInstance());
        row.createCell(6).setCellValue("a string");
        row.createCell(7).setCellValue(true);
        row.createCell(8).setCellType(CellType.ERROR);

        try {
            OutputStream fileOut = new FileOutputStream("workbook.xls");
            wb.write(fileOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3.4 讀取與獲取Excel

使用 File 的方式讀取 Excel

    public static void OpenExcelByFile(){
       try {
           Workbook wb = WorkbookFactory.create(new File("workbook.xls"));
           //讀取
           Sheet sheet=wb.getSheetAt(0);//第一個
           Sheet sheet1=wb.getSheet("sheet1");//根據名稱讀取
           Row row=sheet.getRow(0);//獲取行
           Cell cell=row.getCell(0);//獲取第一行

       }catch (Exception ex){

       }

   }

使用 FileInputStream 需要內存支持

public static void OpenExcelByFileInputStream(){
       try {
           Workbook wb = WorkbookFactory.create(new FileInputStream("workbook.xls"));
           //遍歷
       }catch (Exception ex){

       }
   }

參考:

https://poi.apache.org/

https://www.iteye.com/blog/chenhailong-1498528


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM