duhuizhe
2024-04-17 c389984b5d3e5523e1b22de1fc045dc415261330
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
package com.yqzx.common.util;
// @formatter:off
import cn.jiguang.common.utils.StringUtils;
import lombok.val;import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
 
import javax.servlet.http.HttpServletResponse;import java.net.URLEncoder;import java.util.Date;import java.util.List;import java.util.Locale;
import java.util.Map;
 
/**
 *                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
 *            __.'  @Author     ~.   .~    代码无Bug   `.__
 *          .'//     liu.q        \./       (秘籍)      \\`.
 *        .'// [916000612@qq.com]  |   欲练神功   引刀自宫  \\`.
 *      .'// .-~"""""""~~~~-._     |    _,-~~~~"""""""~-.  \\`.
 *    .'//.-"  2019-07-17     `-.  |  .-'     16:54       "-.\\`.
 *  .'//______.============-..   \ | /   ..-============.______\\`.
 *.'______________________________\|/______________________________`.
 *
 * @Description :
 */
// @formatter:on
 
public class ExportExcel {
    public static void exportExcel(String fileName, List<String> titles, List<List<Object>> rows, HttpServletResponse response) throws Exception {
 
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 18);
 
        //设置标题
        HSSFRow title = sheet.createRow(0);
        for (int i = 0; i < titles.size(); i++) {
            HSSFCell cell = title.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(titles.get(i));
            cell.setCellValue(text);
        }
 
        //设置数据
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        for(int i=0;i<rows.size();i++){
            HSSFRow row = sheet.createRow(i+1);
            List<Object> clo = rows.get(i);
            int index = 0;
            for(Object o :clo){
                HSSFCell cell = row.createCell(index);
                if(o instanceof Date){
                    HSSFDataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("yyyy-mm-dd HH:mm:ss"));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue((Date)o);
                }else if(o instanceof Double){
                    HSSFDataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("#,##0.00"));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(Double.valueOf(o.toString()));
                }else{
                    HSSFDataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("@"));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(o.toString());
                }
                index++;
 
            }
        }
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
 
        //解决 苹果浏览器乱码问题
        val ua = CommonUtil.getRequest().getHeader("User-Agent").toLowerCase(Locale.ENGLISH);
        if (ua.indexOf("macintosh") > -1 && ua.indexOf("chrome") < 0) {
            fileName = new String(fileName.getBytes(), "iso8859-1");
        } else {
            fileName = URLEncoder.encode(fileName, "utf-8");
        }
 
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
    public static void exportExcel(String fileName, List<String> titles, List<List<Object>> rows, Map<String,String> option, HttpServletResponse response) throws Exception {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 18);
 
        //设置标题
        HSSFRow title = sheet.createRow(0);
        for (int i = 0; i < titles.size(); i++) {
            HSSFCell cell = title.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(titles.get(i));
            cell.setCellValue(text);
            if(option!=null && !option.isEmpty()){
                String op = option.get(titles.get(i));
                if(StringUtils.isNotEmpty(op)){
                    // 设置第一列的1-10行为下拉列表
                    CellRangeAddressList regions = new CellRangeAddressList(1, rows.size(), i, i);
                    // 创建下拉列表数据
                    DVConstraint constraint = DVConstraint.createExplicitListConstraint(op.split(","));
                    // 绑定
                    HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
                    sheet.addValidationData(dataValidation);
                }
            }
 
        }
 
        //设置数据
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        for(int i=0;i<rows.size();i++){
            HSSFRow row = sheet.createRow(i+1);
            List<Object> clo = rows.get(i);
            int index = 0;
            for(Object o :clo){
                HSSFCell cell = row.createCell(index);
                if(o instanceof Date){
                    HSSFDataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("yyyy-mm-dd HH:mm:ss"));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue((Date)o);
                }else if(o instanceof Double){
                    HSSFDataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("#,##0.00"));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(Double.valueOf(o.toString()));
                }else{
                    HSSFDataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("@"));
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(o.toString());
                }
                index++;
 
            }
        }
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
 
        //解决 苹果浏览器乱码问题
        val ua = CommonUtil.getRequest().getHeader("User-Agent").toLowerCase(Locale.ENGLISH);
        if (ua.indexOf("macintosh") > -1 && ua.indexOf("chrome") < 0) {
            fileName = new String(fileName.getBytes(), "iso8859-1");
        } else {
            fileName = URLEncoder.encode(fileName, "utf-8");
        }
 
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
 
 
    /**
     * @Description : Excel导出自适应宽度工具类
     * @Author : wh
     * @Date: 2021/10/20 - 11:43
     */
    public static void setSizeColumn2(Sheet sheet, int size) {
        for (int i = 0; i <= size; i++) {
            //int orgWidth = sheet.getColumnWidth(i);
            // sheet.autoSizeColumn(i, true);
            sheet.setColumnWidth(i, 5000);
        }
    }
}