java批量導入導出(poi)

一、批量導入      

1、導入時我們接參時使用MultipartFile來接受excel文件,用poi來讀取文件內容

       InputStream inputStream = MultipartFile.getInputStream();
       Workbook wb = WorkbookFactory.create(inputStream);

2、獲取某個sheet

       Sheet sheet = wb.getSheetAt(0);

3、 獲取sheet的行數
      int rowlNum = sheet.getLastRowNum()

4、獲取sheet的第一行

      Row row = sheet.getRow(e);

5、獲取某一行的的某一列(即是一個單元格)
      Cell cell0 = row.getCell(0);

6、獲取某個單元格爲字符串
      cell0.getRichStringCellValue()

7、 獲取某個單元格爲數字類型
      cell0.getNumericCellValue()

注:在導入中要注意對文件格式的判斷,對文件大小的判斷,對單元格中文本類型的處理,當然要記得關流

 

二、批量導出,既然是導出我們用到輸出流,在控制層參數中加入HttpServletResponse,利用XLSTransformer對象將內容封裝爲導出文件,

                XLSTransformer transformer = new XLSTransformer();
                //將讀取的內容放入map
                Map<String, Object> beanParams = new HashMap<String, Object>();
                beanParams.put("content", content);

                //讀取模板文件
                Resource resource = new ClassPathResource("template/export_item_template.xlsx");
                BufferedInputStream is = new BufferedInputStream(resource.getInputStream());
                Workbook workbook = transformer.transformXLS(is, beanParams);

                //當然要對sheet的單元格合併進行控制

                Sheet sheetAt = workbook.getSheetAt(0);
                CellRangeAddress cellRangeAddress = new CellRangeAddress(FirstRowNum, LastRowNum, 3, 3);
                sheetAt.addMergedRegion(cellRangeAddress);(可以對導出的內容遍歷[content]來計算你需要合併的所有單元格)

                //當然最重要的一筆就是你的模板腳本要正確(spu的集合中包含了sku集合,每一位sku中又包含了shopSupplyInfos集合,注意循環嵌套後一個屬性會打印多次,但是當你對單元格合併進行控制之後此問題可以解決[也正是你所需要的樣式])

               

 

 

:包版本級是比較落後的了

        <!-- poi-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>

        <dependency>
            <groupId>net.sf.jxls</groupId>
            <artifactId>jxls-core</artifactId>
            <version>1.0.6</version>
        </dependency>

 

三、也可以用阿里的導出插件

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.1.6</version>
</dependency>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章