Java通过poi创建文件并分页add数据

maven依赖

        <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>

代码示例

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 java.util.*;

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

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtils.class);

    /**
     * 以下测试方法,先生成一个excel文件,并设置sheet的名称,设置excel头
     * 之后,以分页的方式,向文件中增加数据
     *
     * @param args
     */
    public static void main(String[] args) throws IOException {
        String fileAbsolutePath = "D:\\test.xlsx";
        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 = new ArrayList<DataForExcel>();
        dataForExcelList1.add(new DataForExcel(0, 0, "序号"));
        dataForExcelList1.add(new DataForExcel(0, 1, "姓名"));
        dataForExcelList1.add(new DataForExcel(0, 2, "性别"));
        dataForExcelList1.add(new DataForExcel(0, 3, "家庭住址"));
        dataForExcelList1.add(new DataForExcel(0, 4, "通信地址"));
        dataForExcelList1.add(new DataForExcel(0, 5, "手机号"));
        dataMap.put("人员明细", dataForExcelList1);
        return dataMap;
    }

    /**
     * 传入数据,在指定路径下生成Excel文件 支持生成多个sheet,并为sheet命名
     *
     * @param absolutePath    生成文件的绝对路径,例如"C:\\Users\\...\\out.xlsx"
     * @param dataForExcelMap key:sheet名; value:传入的数据 名字相同时会覆盖之前的文件
     * @return
     */
    public static boolean generateExcelWithManySheets(String absolutePath, Map<String, List<DataForExcel>> dataForExcelMap) {
        boolean flag = false;
        try {
            XSSFWorkbook workbook = 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());
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        return flag;
    }

    /**
     * 向已存在的excel中追加数据
     *
     * @param absolutePath 已存在的excel绝对路径
     * @param sheetIndex   sheet的序号,从0开始
     * @param dataList     cell数据
     * @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的行号 从0开始 例如excel一个表格行号为0,列号也为0
     */
    private Integer row;
    /**
     * excel的列号 从0开始 例如excel一个表格行号为0,列号也为0
     */
    private Integer column;
    /**
     * 插入的值
     */
    private String value;

    public DataForExcel() {
    }

    public DataForExcel(Integer row, Integer column, String value) {
        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;
    }
}

执行截图

原文地址:https://www.cnblogs.com/zhenyuyaodidiao/p/11793976.html

时间: 2024-10-25 11:51:37

Java通过poi创建文件并分页add数据的相关文章

java io流 创建文件、写入数据、设置输出位置

java io流 创建文件 写入数据 改变system.out.print的输出位置 //创建文件 //写入数据 //改变system.out.print的输出位置 import java.io.*; public class Index{ public static void main(String[] args) throws Exception{ /** * 存储为二进制,给计算机看的 */ //创建文件 DataOutputStream sjl = new DataOutputStrea

Windows下Java File对象创建文件夹时的一个"坑"

import java.io.File; import java.io.IOException; public class DirCreate { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String dirStr="D:"; File dir=new File(dirStr); System.out.println("====

Java利用POI导入导出Excel中的数据

     首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地址http://poi.apache.org/download.html,有兴趣的朋友也可以去看看其中的API.      下面分享一下在对POI进行基本操作时觉得需要注意的两点:       1.POI中针对xlsx/xls是需要create different Workbook instance

主库添加数据文件后,备库因为创建文件失败而停止数据同步

primary环境:11gR2 RAC+ASMstandby环境:本地单机 主库添加数据文件后,备库因为创建文件失败而停止数据同步. 1.查看主库环境的数据文件 SQL> select file#,status,name from v$datafile; FILE# STATUS NAME ---------- ------- -------------------------------------------- 1 SYSTEM +ABCE/test/datafile/system.293.

java使用poi创建excel文件

import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem; 注:此方法创

java中file创建文件

import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringBufferInputStream; public class InputStream1 { //Inputstream 字节输入流 //Reader 字符输入流 public static void main(String[] a

java中io创建文件和读取文件

简单了解IO流:https://www.cnblogs.com/weibanggang/p/10034325.html package com.wbg.iodemo1128; import java.io.*; public class OutputStreamDemo { public static void main(String[] args) throws IOException { reader(); } //输入字节流inputStream static void inputStre

java使用POI实现excel文件的读取,兼容后缀名xls和xlsx

需要用的jar包如下: 如果是maven管理的项目,添加依赖如下: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </depen

JAVA用POI读取和创建2003和2007版本Excel完美示例

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import j