Learning to read and write Excel's java poi

A, Excel writes

  In Excel provides us with two types of files and .XLSX .XLS file, read the way these two documents are the same .xls file using HSSF objects, .xlsx using XSSF object because in two ways is the same, so we look at an example of reading HSSF

  1. Import maven

 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
        <!--时间工具类-->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.1</version>
        </dependency>

  2.Excel writes

  Let us take a look at the final table to be generated:

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.*;
import org.joda.time.DateTime;


import java.io.FileOutputStream;
public class Demo {


    public static void main(String[] args) throws Exception {
        showHSSF();
    }


    /**
     * HSSF spreadsheet file to write
     * 
     */
    public static void showHSSF() throws Exception {

        // First create an Excel workbook 
        Workbook Workbook = new new HSSFWorkbook ();

        // build a workbook in Excel worksheet that create sheet, called the test table 
        Sheet sheet = workbook.createSheet ( "Test Form" );

        // create a row, the two rows created
         // value of 0 indicates a first row 
        Row = ROW1 sheet.createRow (0 );

        // value of 1 indicates the second row 
        Row = ROW2 sheet.createRow (1 );

        // Create cell style 
        the CellStyle CellStyle = workbook.createCellStyle ();
         // Sets the horizontal alignment of the pattern is centered; 
        cellStyle.setAlignment (HSSFCellStyle.ALIGN_CENTER);
         // Sets the vertical alignment pattern is centered; 
        cellStyle.setVerticalAlignment ( HSSFCellStyle.VERTICAL_CENTER);

        // create cells
         // this cell position: 1-1 
        the Cell row1Cell1 = row1.createCell (0 );
         // to a cell assignment 
        row1Cell1.setCellValue ( "name" );
         // set the style 
        row1Cell1.setCellStyle (cellStyle) ;

        // this cell position: 1-2 
        the Cell row1Cell2 row1.createCell = (. 1 );
        row1Cell2.setCellValue ( "Age" );
        row1Cell2.setCellStyle(cellStyle);

        // this cell position: merging unit cells 1-3 and 1-4 of 
        the Cell row1Cell3to4 = row1.createCell (2 );
        row1Cell3to4.setCellValue ( "course" );
        row1Cell3to4.setCellStyle(cellStyle);
        // Merge cells (four parameters, namely the start line, the end of the row, starting column, ending column)
         // table row and column start with 0 
        CellRangeAddress coursRegion = new new CellRangeAddress (0, 0, 2, 3 );
        sheet.addMergedRegion(coursRegion);


        // this cell position: 2-1 
        the Cell row2Cell1 = row2.createCell (0 );
        row2Cell1.setCellValue("小明");
        row2Cell1.setCellStyle(cellStyle);

        // this cell position: 2-2 
        the Cell row2Cell2 row2.createCell = (. 1 );
        row2Cell2.setCellValue(16);
        row2Cell2.setCellStyle(cellStyle);

        // this cell position: 2-3 
        the Cell row2Cell3 = row2.createCell (2 );
        row2Cell3.setCellValue ( "Chinese" );
        row2Cell3.setCellStyle(cellStyle);

        // this cell position: 2-4 
        the Cell row2Cell4 row2.createCell = (. 3 );
        row2Cell4.setCellValue ( "Mathematics" );
        row2Cell4.setCellStyle(cellStyle);

        // this cell position: Cells of 1-5,2-5
         // to be noted that if it is combined with the row line must be assigned to a cell in the first row 
        Cell row1to2Cell5 = row1.createCell (4 );
        String dateTime = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
        row1to2Cell5.setCellValue(dateTime);
        row1to2Cell5.setCellStyle(cellStyle);

        // merge cells
         // merged cell (four parameters, namely the start line, the end of the row, starting column, ending column)
         // row and column of the table are from 0 
        CellRangeAddress timeRegion = new new CellRangeAddress (0 , 1,4,4 );
        sheet.addMergedRegion(timeRegion);

        // output file 
        FileOutputStream OUT = new new FileOutputStream ( "E: \\ \\ static POI \\ write test workbook .xls" );
        workbook.write(out);
        // operation is completed, close the file 
        out.close ();
        System.out.println ( "File successfully generated" );
    }
}

  Two modes of operation HSSF XSSF files and documents is the same, but the two have very different: HSSF write fast, but can only write data 65536; XSSF able to write large amounts of data, but write speed very slow, followed by XSSF write operation is to write data directly in memory, and then written to disk copy, which would cause problems of memory overflow, so in order to solve the memory leak problem, poi we offer a promising object SXSSF operating .XSLX file.

  Because the file is written in memory, so we need to clean up a memory operation, add the code after closing the file:

((SXSSFWorkbook)workbook).dispose();

Two, Excel read operation

  Read the two documents there is no difference, but the most important thing is to read the reading of different data types:

  We want to read the table of contents, note that the column is the sum formula H column F and G columns come:

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.joda.time.DateTime;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

public class Demo1 {


    public static void main(String[] args) throws Exception {
        FileName String = "E: \\ \\ static POI \\ test workbook .xls" ;
        readExcel(fileName);

    }

    public  static  void readExcel (String fileName) throws Exception {
         // read file 
        the InputStream inputStream = new new the FileInputStream (fileName);
         // find workbook 
        the Workbook Workbook = new new HSSFWorkbook (inputStream);
         // find the corresponding tables Sheet, 0 represents a Sheet 
        Sheet Sheet workbook.getSheetAt = (0 );
         // get the number of physical lines 
        int the rowCount = sheet.getPhysicalNumberOfRows ();
         // the number of physical lines, read the contents of each cell 
        for ( int rowNum = 0; rowNum < rowCount; rowNum ++) {
             // read the contents of each row 
            Row, rowData = sheet.getRow (rowNum);
             // null pointer Analyzing 
            IF ! (, RowData = null ) {
                 // get the number of physical column, total number of columns 
                int CellCount = rowData.getPhysicalNumberOfCells ();
                 // read the data in each cell 
                for ( int cellNum = 0; cellNum <CellCount; cellNum ++ ) {
                     // read the data cell objects
                     // cell object has a plurality of types of data 
                    the cell cell = , rowData. getCell (cellNum);
                     // null pointer is determined 
                    if(! Cell = null ) {
                         // get the current cell's data type 
                        int celltype = cell.getCellType ();
                         // value of the final read 
                        String CellValue = "" ;
                         // read the data according to the type of cell data 
                        switch (celltype) {
                             // string type 
                            Case HSSFCell.CELL_TYPE_STRING:
                                Of System.out.print ( "Data type String:" );
                                 // string type data acquiring method 
                                CellValue = cell.getStringCellValue ();
                                 BREAK ;
                             // Boolean type, generally will not see the value of this type of 
                            Case HSSFCell.CELL_TYPE_BOOLEAN :
                                Of System.out.print ( "Boolean data type:" );
                                 // boolean data acquisition method 
                                CellValue = String.valueOf (cell.getBooleanCellValue ());
                                 BREAK ;
                             // null data 
                            Case HSSFCell.CELL_TYPE_BLANK:
                                Of System.out.print ( "empty Data:" );
                                 BREAK ;
                             // Value Type
                             // value of a total of two types, values, and timestamps 
                            Case HSSFCell.CELL_TYPE_NUMERIC:
                                 // determines whether the current value of a time stamp 
                                IF (HSSFDateUtil.isCellDateFormatted (Cell)) {
                                    Of System.out.print ( "Date:" );
                                     // time data type conversion 
                                    a Date DATE = cell.getDateCellValue ();
                                    cellValue = new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
                                } The else {
                                     // not a date format, when the number is too long to prevent the display in scientific notation 
                                    System.out.print ( "numeric types of data:" );
                                     // numeric type data into a string type 
                                    cell.setCellType (HSSFCell.CELL_TYPE_STRING);
                                    cellValue = cell.toString();
                                }
                                BREAK ;
                             // formula type data 
                            Case HSSFCell.CELL_TYPE_FORMULA:
                                 // get cell formulas using 
                                String Formula = cell.getCellFormula ();
                                Of System.out.print ( "cell formula is used:" + Formula);
                                 // get the calculated data 
                                Double value = cell.getNumericCellValue ();
                                Of System.out.print ( "data is calculated:" + value);
                                 BREAK ;
                             // incorrect data type 
                            Case Cell.CELL_TYPE_ERROR:
                                Of System.out.print ( "wrong data type" );
                                 BREAK ;
                        }

                        System.out.println(cellValue);

                    }

                }

            }

        }
        inputStream.close();
    }
}

  Test content:

 

 

  

 

Guess you like

Origin www.cnblogs.com/daijiting/p/12284417.html