当前位置:网站首页>Reading and writing Apache poi

Reading and writing Apache poi

2022-06-27 09:07:00 Midsummer 28

POI-Excel

Frequently used information

  1. Export user information as excel form ( For example, export data : database information )
  2. take excel The information in the table is entered into the website database ( For example, import data : Question bank )

Development often uses excel To deal with , For example, import 、 export excel

operation Excel What's more popular at present is Apache POI And Alibaba's easyExcel

Apache POI( It will be more troublesome )

Official website :Apache POI - the Java API for Microsoft Documents

Baidu profile :

Apache POI [1] Yes, it is Java Write free open source cross platform Java API,Apache POI Provide API to Java Program pair [Microsoft Office](https://baike.baidu.com/item/Microsoft Office) Format file reading and writing functions .POI by “Poor Obfuscation Implementation” An acronym for , Meaning for “ Simple version of fuzzy implementation ”.

structure :

 Insert picture description here


easyExcel(alibaba)

Official website :https://github.com/alibaba/easyexce or EasyExcel · Language sparrow (yuque.com)

 Insert picture description here

EasyExcel Alibaba is an open source excel Processing framework , With Easy to use , Save memory

EasyExcel It's based on Java Simple 、 Save memory for reading and writing Excel Open source projects for . In the case of saving memory as much as possible, it supports reading and writing M Of Excel.

EasyExcel The main reason that can greatly reduce the memory occupation is parsing Excel The file data is not loaded into memory at one time , Instead, read data from a row on the disk , One by one .

File decompression, file reading through file form

img

POI-Excel Write

Create project

  1. Create a new project

  2. introduce pom rely on

     <!-- Import dependence -->
        <dependencies>
            <!--03-->
             <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>4.1.0</version>
            </dependency>
             <!--07-->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>4.1.0</version>
            </dependency>
            <!-- Date formatting tool -->
            <dependency>
                <groupId>joda-time</groupId>
                <artifactId>joda-time</artifactId>
                <version>2.10.1</version>
            </dependency>
            <!--test-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
  3. The popular science :03 Version of execl and 07 Version of execl What's the difference ?

  4. 03 And 07 Differences in versions :

    03 edition

     @Test
        public void test03() throws IOException {
          
            // Create a workbook 
            Workbook workbook = new HSSFWorkbook();
            // Create a worksheet 
            Sheet sheet = workbook.createSheet(" Li Kai's worksheet ");
            // Create lines 
            Row row = sheet.createRow(0);
            // Create cell grids ((0,0)
            Cell cell = row.createCell(0);
            /* Add content */
            cell.setCellValue(" Spend today ");
            //(0,1)
            Cell cell1 = row.createCell(1);
            cell.setCellValue("20");
            /*1,0*/
            final Row row1 = sheet.createRow(1);
            final Cell cell2 = row1.createCell(0);
            cell2.setCellValue(" Count the time ");
            final String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss:sss");
            final Cell cell3 = row1.createCell(1);
            /* Put in time */
            cell3.setCellValue(time);
            /* Generate a table  03 Version USES xls ending */
            FileOutputStream fileOutputStream = new FileOutputStream(PATH + " Li Kai's sunrise consumption table .xls");
            workbook.write(fileOutputStream);
            // Closed flow 
            fileOutputStream.close();
            workbook.close();
            System.out.println(" Generation completed ");
        } 
    

    07 edition

    public void test07() throws IOException {
          
            // Create a workbook 
            Workbook workbook = new XSSFWorkbook();
            // Create a worksheet 
            Sheet sheet = workbook.createSheet(" Li Kai's worksheet ");
            // Create lines 
            Row row = sheet.createRow(0);
            // Create cell grids ((0,0)
            Cell cell = row.createCell(0);
            /* Add content */
            cell.setCellValue(" Spend today ");
            //(0,1)
            Cell cell1 = row.createCell(1);
            cell1.setCellValue("20");
            /*1,0*/
             Row row1 = sheet.createRow(1);
            Cell cell2 = row1.createCell(0);
            cell2.setCellValue(" Count the time ");
            final String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss:sss");
            final Cell cell3 = row1.createCell(1);
            /* Put in time */
            cell3.setCellValue(time);
            /* Generate a table  03 Version USES xls ending */
            FileOutputStream fileOutputStream = new FileOutputStream(PATH + " Li Kai's sunrise consumption table .xlsx");
            workbook.write(fileOutputStream);
            // Closed flow 
            fileOutputStream.close();
            workbook.close();
            System.out.println(" Generation completed ");
        }
    

    difference :

    1. The difference between objects

      03 edition : Workbook workbook = new HSSFWorkbook();

      07 edition :Workbook workbook = new XSSFWorkbook();

    2. The difference between suffixes

      0307
      xlsxlsx
  5. 03 Version of large file write

shortcoming : Only... Can be written at most 65536 That's ok , Otherwise, an exception will be thrown

java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)

advantage : Write cache in process , Do not operate disk , The last one-time write to disk , Fast

Time :
 Insert picture description here

Correct code :

 public void test03BigData() throws IOException {
    
        //  Time difference :
        final long begin = System.currentTimeMillis();

        // Create a workbook 
        Workbook workbook = new HSSFWorkbook();
        // Create table 
        final Sheet sheet = workbook.createSheet();
        // Write data 
        for (int rowNum = 0;rowNum<65536;rowNum++){
    
            final Row row = sheet.createRow(rowNum);
            for (int cellNum = 0;cellNum<10;cellNum++){
    
                final Cell cell = row.createCell(cellNum);
                cell.setCellValue(cellNum);
            }
        }
        System.out.println("over");
        final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xls");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        final long end = System.currentTimeMillis();
        System.out.println((double)(end-begin)/1000);
    }

Error code :

public void test03BigData() throws IOException {
    
    //  Time difference :
    final long begin = System.currentTimeMillis();

    // Create a workbook 
    Workbook workbook = new HSSFWorkbook();
    // Create table 
    final Sheet sheet = workbook.createSheet();
    // Write data 
    for (int rowNum = 0;rowNum<65537;rowNum++){
    
        final Row row = sheet.createRow(rowNum);
        for (int cellNum = 0;cellNum<10;cellNum++){
    
            final Cell cell = row.createCell(cellNum);
            cell.setCellValue(cellNum);
        }
    }
    System.out.println("over");
    final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xls");
    workbook.write(fileOutputStream);
    fileOutputStream.close();
    final long end = System.currentTimeMillis();
    System.out.println((double)(end-begin)/1000);
}
  1. 07 Version of large file write

    shortcoming : When writing data, the data speed is very slow , Very memory intensive , There will also be spills , Such as 100w Data

    advantage : You can write a large amount of data , Such as 20w Data

    Time :
     Insert picture description here

    You can find even one more piece of data , There will be more time 4 times

    Code :

    public void test07BigData() throws IOException {
          
        //  Time difference :
        final long begin = System.currentTimeMillis();
    
        // Create a workbook 
        Workbook workbook = new XSSFWorkbook();
        // Create table 
        final Sheet sheet = workbook.createSheet();
        // Write data 
        for (int rowNum = 0;rowNum<65537;rowNum++){
          
            final Row row = sheet.createRow(rowNum);
            for (int cellNum = 0;cellNum<10;cellNum++){
          
                final Cell cell = row.createCell(cellNum);
                cell.setCellValue(cellNum);
            }
        }
        System.out.println("over");
        final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xlsx");
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        final long end = System.currentTimeMillis();
        System.out.println((double)(end-begin)/1000);
    }
    
  2. 07 Version of big data write SXSSF

    advantage : Can write a very large amount of data , for example 100w Pieces of data or even more , be relative to 07 Version of XSSF, He reads and writes data faster , Less memory

    Be careful : Temporary files are generated in the process , Need to clean up temporary files

    By default 100 Records are stored in memory , If you exceed that amount , The first data will be written to the temporary file .

    If you want to customize the amount of data in memory , You can use the new SXXSFWorkbook( Number )

    Time :
     Insert picture description here

    Code :

     public void test07BigDataS() throws IOException {
          
            //  Time difference :
            final long begin = System.currentTimeMillis();
    
            // Create a workbook 
            Workbook workbook = new SXSSFWorkbook();
            // Create table 
            final Sheet sheet = workbook.createSheet();
            // Write data 
            for (int rowNum = 0;rowNum<65537;rowNum++){
          
                final Row row = sheet.createRow(rowNum);
                for (int cellNum = 0;cellNum<10;cellNum++){
          
                    final Cell cell = row.createCell(cellNum);
                    cell.setCellValue(cellNum);
                }
            }
            System.out.println("over");
            final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xlsx");
            workbook.write(fileOutputStream);
            fileOutputStream.close();
            /* Clear temporary files */
            ((SXSSFWorkbook)workbook).dispose();
            final long end = System.currentTimeMillis();
            System.out.println((double)(end-begin)/1000);
        }
    

POI-Excel read

07/03 edition

@Test
public void test03() throws IOException {
    

    // Get file stream 
    FileInputStream fileInputStream = new FileInputStream(PATH+"ABC.xls");
    // Create a workbook . Use excel Any operation that can be completed can be completed here 
    Workbook workbook = new HSSFWorkbook(fileInputStream);
    // Get the table 
    final Sheet sheetAt = workbook.getSheetAt(0);
    /* Get row */
    final Row row = sheetAt.getRow(0);
    final int RowNum = sheetAt.getLastRowNum();
    /* Get column */
    final Cell cell = row.getCell(0);
    final String stringCellValue = cell.getStringCellValue();
    System.out.println(stringCellValue);
    System.out.println(RowNum);
    fileInputStream.close();
}

07 edition :

@Test
public void test03() throws IOException {
    

    // Get file stream 
    FileInputStream fileInputStream = new FileInputStream(PATH+"ABC.xlsx");
    // Create a workbook . Use excel Any operation that can be completed can be completed here 
    Workbook workbook = new XSSFWorkbook(fileInputStream);
    // Get the table 
    final Sheet sheetAt = workbook.getSheetAt(0);
    /* Get row */
    final Row row = sheetAt.getRow(0);
    final int RowNum = sheetAt.getLastRowNum();
    /* Get column */
    final Cell cell = row.getCell(0);
    final String stringCellValue = cell.getStringCellValue();
    System.out.println(stringCellValue);
    System.out.println(RowNum);
    fileInputStream.close();
}

Read different data types

a key : Data conversion type !

  @Test
    public void test07Demo() throws IOException {
    

        // Get file stream 
        FileInputStream fileInputStream = new FileInputStream(PATH+"ABC.xlsx");
        // Create a workbook . Use excel Any operation that can be completed can be completed here 
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        // Get the table 
        Sheet sheetAt = workbook.getSheetAt(0);
        /* Get the number of lines */
        Row row = sheetAt.getRow(0);
        if (row!=null){
    
            /* Get the number of all rows */
            final int physicalNumberOfCells = row.getPhysicalNumberOfCells();
            for (int CellNum = 0; CellNum < physicalNumberOfCells; CellNum++) {
    
                final Cell cell = row.getCell(CellNum);
                if (cell!=null){
    
                    /* Get the type of row */
                    CellType cellType = cell.getCellType();
                    String stringCellValue = cell.getStringCellValue();
                    System.out.print(stringCellValue+" ");
                }
            }
            System.out.println();
        }
        // Get the data in the table ( Number of columns )
        int physicalNumberOfRows = sheetAt.getPhysicalNumberOfRows();
        for (int RowNum = 1; RowNum < physicalNumberOfRows; RowNum++) {
    
            final Row row1 = sheetAt.getRow(RowNum);
            if (row1!=null){
    
                // Read column 
                final int physicalNumberOfCells = row1.getPhysicalNumberOfCells();
                for (int cellNumber = 0; cellNumber < physicalNumberOfCells; cellNumber++) {
    
                    final Cell cell = row1.getCell(cellNumber);
                    // Match the data type of the column 
                    if (cell!=null){
    
                        CellType cellType = cell.getCellType();
                        String cellValue = "";
                        /* Judgment type */
                        switch (cellType){
    
                            case STRING:
                                System.out.println(" character string ");
                                cellValue= cell.getStringCellValue();
                                break;
                            case BOOLEAN:
                                System.out.println(" Boolean type ");
                                cellValue = String.valueOf(cell.getBooleanCellValue());
                                break;
                            case BLANK:
                                System.out.println(" It's empty ");
                                break;
                            case NUMERIC: // Numbers ( Dates and ordinary numbers )
                                if (HSSFDateUtil.isCellDateFormatted(cell)){
     // date 
                                    System.out.println(" The date type ");
                                    Date date = cell.getDateCellValue();
                                    cellValue = new DateTime(date).toString("yyyy-MM-dd");
                                }else {
    
                                    System.out.println(" Numbers ");
                                    cellValue = String.valueOf(cell.getNumericCellValue());
                                }
                                break;
                            case ERROR:
                                System.out.println(" Wrong array type ");
                                break;
                        }
                        System.out.println(cellValue);
                    }
                }
            }
        }
        fileInputStream.close();
    }

Calculation formula :

 @Test
    public void testFormula() throws IOException {
    
       FileInputStream fileInputStream = new FileInputStream(PATH + "Documents test .xlsx");
       Workbook workbook= new XSSFWorkbook(fileInputStream);
       Sheet sheetAt = workbook.getSheetAt(0);
       Row row = sheetAt.getRow(4);
       Cell cell = row.getCell(0);
       // Get the formula  eval
        FormulaEvaluator xssfFormulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
        // Output the contents of the cell 
        CellType cellType = cell.getCellType();
        switch (cellType){
    
            case FORMULA: // The formula 
               String cellFormula = cell.getCellFormula();
                System.out.println(cellFormula);
               // Calculation 
                CellValue evaluate = xssfFormulaEvaluator.evaluate(cell);
                String CellValue = evaluate.formatAsString();
                System.out.println(CellValue);
                break;
        }
    }
原网站

版权声明
本文为[Midsummer 28]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270855247222.html