Java poi by creating a file and add data paging

maven dependence

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

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.12</version>
        </dependency>

 

The sample code

package com.**.**.**.common.utils;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import* Classes in java.util. ; 

/ ** 
 * @author zyydd 
 * @date 2019/3/15 15:00 
 * / 
public  class ExcelUtils { 

    Private  static  Final Logger LOGGER = LoggerFactory.getLogger (ExcelUtils. class ); 

    / ** 
     * less test method, as a Mr excel file, and the name of sheet set is provided excel head 
     after *, in paging mode, to increase the data file 
     * 
     * @param args
      * / 
    public  static  void main (String [] args) throws IOException { 
        String fileAbsolutePath = "D: \\ test.xlsx" ; 
        the Map<String, List<DataForExcel>> dataMap = initTestDataHead();
        ExcelUtils.generateExcelWithManySheets(fileAbsolutePath, dataMap);
        for (int i = 0; i < 3; i++) {
            List<String[]> testData = new ArrayList<>();
            for (int k = 1; k < 11; k++) {
                String[] oneRow = new String[6];
                oneRow[0] = (i * 10 + k) + "";
                oneRow[1] = "张三" + oneRow[0];
                oneRow[2] = "男";
                oneRow[3] = "北京市朝阳区";
                oneRow[4] = "北京市大兴区";
                oneRow[5] = (System.currentTimeMillis() % 10000000000L) + "";
                testData.add(oneRow);
            }
            ExcelUtils.addExcel(fileAbsolutePath, 0, testData);
        }
    }

    private static Map<String, List<DataForExcel>> initTestDataHead() {
        Map<String, List<DataForExcel>> dataMap = new HashMap<String, List<DataForExcel>>();
        List<DataForExcel> dataForExcelList1 = newThe ArrayList <DataForExcel> (); 
        dataForExcelList1.add ( new new DataForExcel (0, 0, "No." )); 
        dataForExcelList1.add ( new new DataForExcel (0,. 1, "name" )); 
        dataForExcelList1.add ( new new DataForExcel (0, 2, "gender" )); 
        dataForExcelList1.add ( new new DataForExcel (0,. 3, "home address" )); 
        dataForExcelList1.add ( new new DataForExcel (0,. 4, "the communication address" )); 
        dataForExcelList1.add ( new new DataForExcel (0, 5, "phone number" )); 
        dataMap.put ( "personnel details" , dataForExcelList1);
        returnDatamap; 
    } 

    / ** 
     * incoming data, generating a plurality of generated Excel file support sheet at the specified path, and for the sheet name 
     * 
     * @param the absolutePath generate absolute path of the file, such as "C: \\ Users \\ .. . \\ out.xlsx " 
     * @param dataForExcelMap Key: Sheet name; value: incoming data file with the same name will overwrite the previous 
     * @return 
     * / 
    public  static  boolean generateExcelWithManySheets (String absolutePath, the Map <String, List <DataForExcel >> dataForExcelMap) {
         Boolean In Flag = to false ;
         the try { 
            XSSFWorkbook Workbook = new new XSSFWorkbook ();
             for (Map.Entry<String, List<DataForExcel>> entry : dataForExcelMap.entrySet()) {
                XSSFSheet sheet = workbook.createSheet(entry.getKey());
                List<DataForExcel> dataForExcel = entry.getValue();
                Collections.sort(dataForExcel, (arg0, arg1) -> arg0.getRow().compareTo(arg1.getRow()));
                XSSFRow nrow = null;
                for (DataForExcel data : dataForExcel) {
                    if (dataForExcel.indexOf(data) == 0 || !data.getRow().equals(dataForExcel.get(dataForExcel.indexOf(data) - 1).getRow())) {
                        nrow = sheet.createRow(data.getRow());
                    }
                    XSSFCell ncell = nrow.createCell(data.getColumn());
                    ncell.setCellValue(data.getValue());
                }
            }
            File file = new File(absolutePath);
            file.createNewFile();
            FileOutputStream stream = FileUtils.openOutputStream(file);
            workbook.write(stream);
            stream.close();
            flag = true;
        } catch(IOException IE) {
            LOGGER.error (ie.getMessage ()); 
        } the catch (Exception E) { 
            LOGGER.error (e.getMessage ()); 
        } 
        return In Flag; 
    } 

    / ** 
     * append data to the existing excel 
     * 
     * @param excel absolute path absolutePath existing 
     * @param sheetIndex Sheet sequence number, starting from 0 
     * @param dataList Cell data 
     * @return 
     * @throws IOException
      * / 
    public  static Boolean addExcel (String absolutePath, int sheetIndex, List <String []> dataList)throws IOException {
        int columnsNum = dataList.get(0).length;
        FileInputStream fs = new FileInputStream(absolutePath);
        XSSFWorkbook wb = new XSSFWorkbook(fs);
        XSSFSheet sheet = wb.getSheetAt(sheetIndex);
        XSSFRow row;
        int lastRowNum = sheet.getLastRowNum();
        FileOutputStream out = new FileOutputStream(absolutePath);
        for (int i = 0; i < dataList.size(); i++) {
            row = sheet.createRow(++lastRowNum);
            String[] addOneRowData = dataList.get(i);
            for (int j = 0; j < addOneRowData.length; j++) {
                String str = addOneRowData[j];
                row.createCell(j).setCellValue(str);
            }
        }
        setSheetStyle(sheet, columnsNum - 1);
        wb.write(out);
        out.flush();
        out.close();
        return true;
    }

    private static XSSFSheet setSheetStyle(XSSFSheet sheet, int columnsNum) {
        sheet.createFreezePane(0, 1, 0, 1);
        String columnRange = "A1:" + (char) (65 + columnsNum) + "1";
        sheet.setAutoFilter(CellRangeAddress.valueOf(columnRange));
        for (int i = 0; i <= columnsNum; i++) {
            sheet.autoSizeColumn(i);
        }
        return sheet;
    }


}

 

Package ... COM ** ** ** .common.utils; 

/ ** 
 * @author zyydd 
 * @date 2019/3/15 15:00 
 * / 
public  class DataForExcel {
     / ** 
     * Excel row number from 0 for example, a start excel table row number 0, column number is also 0 
     * / 
    Private Integer row;
     / ** 
     * excel column numbers starting from 0, for example, a excel table row number 0, column number is also 0 
     * / 
    Private Integer column;
     / ** 
     * value inserted 
     * / 
    Private String value; 

    public DataForExcel () { 
    } 

    public DataForExcel (Integer Row, column Integer, String value) {
         the this .Row = row;
        this.column = column;
        this.value = value;
    }

    public Integer getRow() {
        return row;
    }

    public void setRow(Integer row) {
        this.row = row;
    }

    public Integer getColumn() {
        return column;
    }

    public void setColumn(Integer column) {
        this.column = column;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

 

Screenshot execution

 

Guess you like

Origin www.cnblogs.com/zhenyuyaodidiao/p/11793976.html