Blame view

ZipTestUtils.java 11.9 KB
涂亚平 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
package com.subsidy.util;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipTestUtils {

     /*
        原链接:https://blog.csdn.net/houxuehan/article/details/89189820
     */

    public static String NO_DEFINE = "no_define";//未定义的字段
    public static String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日";//默认日期格式
    public static int DEFAULT_COLOUMN_WIDTH = 17;

    /**
     * 导出Excel 2007 OOXML (.xlsx)格式
     *
     * @param title       标题行
     * @param headList     属性-列头
     * @param students    数据集
     * @param datePattern 日期格式,传null值则默认 年月日
     * @param colWidth    列宽 默认 至少17个字节
     * @param out         输出流
     */
    public static void exportExcelX(String title, List<String> headList, List<Student> students, String datePattern, int colWidth, OutputStream out) {
        if (datePattern == null) {
            datePattern = DEFAULT_DATE_PATTERN;
        }
        // 声明一个工作薄
        SXSSFWorkbook workbook = new SXSSFWorkbook(1000);//缓存
        workbook.setCompressTempFiles(true);
        //表头样式
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font titleFont = workbook.createFont();
        titleFont.setFontHeightInPoints((short) 20);
        titleFont.setBoldweight((short) 700);
        titleStyle.setFont(titleFont);
        // 列头样式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 12);
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setFont(headerFont);
        // 单元格样式
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        Font cellFont = workbook.createFont();
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        cellStyle.setFont(cellFont);
        // 生成一个(带标题)表格
        SXSSFSheet sheet = workbook.createSheet();
        //设置列宽
        int minBytes = colWidth < DEFAULT_COLOUMN_WIDTH ? DEFAULT_COLOUMN_WIDTH : colWidth;//至少字节数
        int[] arrColWidth = new int[headList.size()];
        // 产生表格标题行,以及设置列宽
        String[] properties = new String[headList.size()];
        String[] headers = new String[headList.size()];
        int ii = 0;
        for (int i = 0 ;i < headList.size(); i++) {

            //properties[ii] = fieldName;
            headers[ii] = headList.get(i);

            int bytes = headList.get(i).getBytes().length;
            arrColWidth[ii] = bytes < minBytes ? minBytes : bytes;
            sheet.setColumnWidth(ii, arrColWidth[ii] * 256);
            ii++;
        }
        // 遍历集合数据,产生数据行
        int rowIndex = 0;
        for (Student student : students) {
            if (rowIndex == 65535 || rowIndex == 0) {
                if (rowIndex != 0) {
                    sheet = workbook.createSheet();//如果数据超过了,则在第二页显示
                }
                SXSSFRow titleRow = sheet.createRow(0);//表头 rowIndex=0
                titleRow.createCell(0).setCellValue(title);
                titleRow.getCell(0).setCellStyle(titleStyle);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headList.size() - 1));

                SXSSFRow headerRow = sheet.createRow(1); //列头 rowIndex =1
                for (int i = 0; i < headers.length; i++) {
                    headerRow.createCell(i).setCellValue(headers[i]);
                    headerRow.getCell(i).setCellStyle(headerStyle);

                }
                rowIndex = 2;//数据内容从 rowIndex=2开始
            }

            SXSSFRow dataRow = sheet.createRow(rowIndex);

            SXSSFCell newCell = dataRow.createCell(0);
            newCell.setCellStyle(cellStyle);
            newCell.setCellValue(student.getName());

            newCell = dataRow.createCell(1);
            //newCell.setCellStyle(cellStyle);
            newCell.setCellValue(student.getAge());

            newCell = dataRow.createCell(2);
            newCell.setCellValue(new SimpleDateFormat(datePattern).format(student.getBirthday()));

            newCell = dataRow.createCell(3);
            newCell.setCellValue(student.getHeight());

            newCell = dataRow.createCell(4);
            newCell.setCellValue(student.getWeight());

            newCell = dataRow.createCell(5);
            newCell.setCellValue(student.isSex());

            //
            //for (int i = 0; i < properties.length; i++) {
            //
            //    Object o = jo.get(properties[i]);
            //    String cellValue = "";
            //    if (o == null) {
            //        cellValue = "";
            //    } else if (o instanceof Date) {
            //        cellValue = new SimpleDateFormat(datePattern).format(o);
            //    }
            //    /*else if(o instanceof Float || o instanceof Double) {
            //    	double d = (double) o;
            //    	if(d%1==0)  cellValue=o.toString();
            //    	else cellValue= new BigDecimal(o.toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            //    }*/
            //    else {
            //        cellValue = o.toString();
            //    }
            //    newCell.setCellValue(cellValue);
            //    newCell.setCellStyle(cellStyle);
            //}
            rowIndex++;
        }
        // 自动调整宽度
        /*for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }*/
        try {
            workbook.write(out);
            workbook.close();
            workbook.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩单个excel文件的输出流 到zip输出流,注意zipOutputStream未关闭,需要交由调用者关闭之
     *
     * @param zipOutputStream   zip文件的输出流
     * @param excelOutputStream excel文件的输出流
     * @param excelFilename     文件名可以带目录,例如 TestDir/test1.xlsx
     */
    public static void compressFileToZipStream(ZipOutputStream zipOutputStream,
                                               ByteArrayOutputStream excelOutputStream, String excelFilename) {
        byte[] buf = new byte[1024];
        try {
            // Compress the files
            byte[] content = excelOutputStream.toByteArray();
            ByteArrayInputStream is = new ByteArrayInputStream(content);
            BufferedInputStream bis = new BufferedInputStream(is);
            // Add ZIP entry to output stream.
            zipOutputStream.putNextEntry(new ZipEntry(excelFilename));
            // Transfer bytes from the file to the ZIP file
            int len;
            while ((len = bis.read(buf)) > 0) {
                zipOutputStream.write(buf, 0, len);
            }
            // Complete the entry
            //excelOutputStream.close();//关闭excel输出流
            zipOutputStream.closeEntry();
            bis.close();
            is.close();
            // Complete the ZIP file
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        int count = 100;
        List<Student> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            Student s = new Student();
            s.setName("POI" + i);
            s.setAge(i);
            s.setBirthday(new Date());
            s.setHeight(i);
            s.setWeight(i);
            s.setSex(i / 2 == 0 ? false : true);
            list.add(s);
        }
        //Map<String, String> headMap = new LinkedHashMap<String, String>();
        //headMap.put("name", "姓名");
        //headMap.put("age", "年龄");
        //headMap.put("birthday", "生日");
        //headMap.put("height", "身高");
        //headMap.put("weight", "体重");
        //headMap.put("sex", "性别");

        List<String> memberList = Arrays.asList(new String[]{"成员名称","账号","联系方式","签到次数","课程进度","培训时长","评级测试","答疑"});


        //导出zip
        OutputStream outXlsx = new FileOutputStream("E://test.zip");
        ZipOutputStream zipOutputStream = new ZipOutputStream(outXlsx);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        exportExcelX("testExcel", memberList, list, null, 0, baos);
        compressFileToZipStream(zipOutputStream, baos, "/test/aaa.xlsx");
        baos.close();

        zipOutputStream.flush();
        zipOutputStream.close();
        outXlsx.close();

        System.out.println("导出zip完成");
    }


    public void exportZip(HttpServletResponse response, List<Student> students) throws Exception {

        ServletOutputStream sos = response.getOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(sos);
        String zipname = "test.zip";
        response.reset();
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((zipname).getBytes(), "iso-8859-1"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        /**
         * 班级成员
         */
        List<String> memberList = Arrays.asList(new String[]{"成员名称","账号","联系方式","签到次数","课程进度","培训时长","评级测试","答疑"});

        /**
         * 注册签到
         */
        List<String> signList = Arrays.asList(new String[]{"成员名称","培训时长","课程进度","完成率"});

        /**
         * 测试成绩
         */
        List<String> scoreList = Arrays.asList(new String[]{"成员名称","测试结果","最高分"});

        /**
         * 答疑记录
         */
        List<String> answerList = Arrays.asList(new String[]{"提问","答疑","提问时间","提问成员","答疑时间"});

        //Map<String, String> headMap = new LinkedHashMap<String, String>();
        //headMap.put("name", "成员名称");
        //headMap.put("age", "年龄");
        //headMap.put("birthday", "生日");
        //headMap.put("height", "身高");
        //headMap.put("weight", "体重");
        //headMap.put("sex", "性别");

        exportExcelX("title", memberList, students, null, 0, baos);
        compressFileToZipStream(zipOutputStream, baos, "/test/aaa.xlsx");
        baos.close();

        zipOutputStream.flush();
        zipOutputStream.close();
        sos.close();
        System.out.println("导出zip完成");
    }

}