文件生成excel文件并将文件夹打包

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15783243/article/details/84893790
工作中遇到需要生成大量的excel文件,然后将所有文件放到一个文件夹下,并打包成zip文件,实现了一下两个工具,以便使用:

1、excel文件写入工具:


package com.research.contactsrepairing.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;


/**
 * Created by glin on 2018/12/7 0007.
 */
public class ExcelUtil {
    public static void exportExcel(JSONArray objects, ServletOutputStream outputStream) throws Exception{
        //1.创建工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 1.1创建合并单元格
        CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 6);

        // 1.2创建标题样式
        CellStyle style1 = createStyle(workbook, 16);
        // 1.3创建列标题样式
        CellStyle style2 = createStyle(workbook, 12);
        // 2.创建工作表
        Sheet sheet = workbook.createSheet("hello world");
        // 设置默认列宽
        sheet.setDefaultColumnWidth(15);
        // 2.1将合并单元格作用于sheet
        sheet.addMergedRegion(cra);
        // 3.创建行
        Row row = sheet.createRow(0);
        // 4.创建单元格
        Cell cell = row.createCell(0);
        // 5.向单元格写入数据
        cell.setCellValue("用户列表");
        // 6.将单元格加入样式
        cell.setCellStyle(style1);

        // 写列标题
        String[] titles = { "用户名", "电话", "注释" };
        // 创建列标题行
        Row row2 = sheet.createRow(1);
        for (int i = 0; i < titles.length; i++) {
            // 创建单元格
            Cell cell1 = row2.createCell(i);
            // 向单元格写入数据
            cell1.setCellValue(titles[i]);
            // 将单元格加入样式
            cell1.setCellStyle(style2);
        }

        for (Object ss:objects) {
            Gson g = new Gson();
            Map<String,String> map = g.fromJson(JSON.toJSONString(ss), Map.class);
            Row rowdata = sheet.createRow( 2);
            // 用户名
            Cell cell0 = rowdata.createCell(0);
            cell0.setCellValue( map.get("name"));
            // 电话
            Cell cell1 = rowdata.createCell(1);
            cell1.setCellValue(map.get("phone"));
            // 注释
            Cell cell2 = rowdata.createCell(2);
            cell2.setCellValue(map.get("remark"));
        }
        // 6.写入硬盘文件
        workbook.write(outputStream);
        workbook.close();
    }

/** 
* 此方法接受三个参数   第一个是需要生成excel的文件,第二个是要把excel保存的路径,第三个是excel生成路径
*/

    public static void exportData(JSONArray objects,String path,String finalXlsxPath) throws Exception{
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String date = df.format(LocalDateTime.now());
        //1.创建工作薄
        //第一步,创建一个workbook对应一个excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        //第二部,在workbook中创建一个sheet对应excel中的sheet
        HSSFSheet sheet = workbook.createSheet("用户表一");
        //第三部,在sheet表中添加表头第0行,老版本的poi对sheet的行列有限制
        HSSFRow row = sheet.createRow(0);
        //第四步,创建单元格,设置表头
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("姓名");
        cell = row.createCell(1);
        cell.setCellValue("电话");
        cell = row.createCell(2);
        cell.setCellValue("备注");
        int i=0;
        for(Object ss:objects){
            HSSFRow row1 = sheet.createRow( i+1);
            Gson g = new Gson();
            Map map = g.fromJson(JSON.toJSONString(ss), Map.class);
            Object name = map.get("name");
            Object phone = map.get("phone");
            Object remark = map.get("remark");
            //创建单元格设值
            row1.createCell(0).setCellValue(String.valueOf(name));
            row1.createCell(1).setCellValue(String.valueOf(phone));
            row1.createCell(2).setCellValue(String.valueOf(remark));
            i++;
        }
        //将文件保存到指定的位置
        try {
            File file=new File(path+"/"+date+"/");
            if(!file.exists()){//如果文件夹不存在
                file.mkdir();//创建文件夹
            }
            FileOutputStream fos = new FileOutputStream(finalXlsxPath);
            workbook.write(fos);
            System.out.println("写入成功");
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //设置样式方法
    public static CellStyle createStyle(Workbook workbook, int fontsize){
        //1.2设置单元格样式
        CellStyle style = workbook.createCellStyle();
        // 设置水平居中
        //style.setAlignment(CellStyle.ALIGN_CENTER);
        // 设置垂直居中
        //style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        // 1.3设置字体
        Font font = workbook.createFont();
        // 设置字体为ARIAL
        font.setFontName(HSSFFont.FONT_ARIAL);
        // 设置粗体
        //font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        // 设置字体颜色
        //font.setColor(HSSFColor.BLUE.index);
        // 设置字体大小
        font.setFontHeightInPoints((short) fontsize);
        // 将字体加入样式
        style.setFont(font);
        return style;
    }

}

2、文件打包工具

package com.research.contactsrepairing.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by glin on 2018/12/8 0008.
 */
public class ZipUtils {
    private static final int  BUFFER_SIZE = 2 * 1024;

        /**
         * 压缩成ZIP 方法1
         * @param srcDir 压缩文件夹路径
         * @param out    压缩文件输出流
         * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
         *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
         * @throws RuntimeException 压缩失败会抛出运行时异常
         */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
        throws RuntimeException{

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

        /**
         * 压缩成ZIP 方法2
         * @param srcFiles 需要压缩的文件列表
         * @param out           压缩文件输出流
         * @throws RuntimeException 压缩失败会抛出运行时异常
         */
    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


        /**
         * 递归压缩方法
         * @param sourceFile 源文件
         * @param zos        zip输出流
         * @param name       压缩后的名称
         * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
         *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
         * @throws Exception
         */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }

            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }

                }
            }
        }

    }

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

        /** 测试压缩方法1  */

        FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip"));

        ZipUtils.toZip("D:/log", fos1,true);

        /** 测试压缩方法2  */
        List<File> fileList = new ArrayList<>();
        fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
        fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));

        FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));

        ZipUtils.toZip(fileList, fos2);

    }
}

猜你喜欢

转载自blog.csdn.net/qq_15783243/article/details/84893790