导出Excel通用模块设计(修订版)

/**
     * 导出Excel文件
     *
     * @param title
     *            String 导出文件的名字
     * @param t_headList
     *            List 表头信息 表头名字——
     *            fieldname,字段名字——field,对齐方式——align,值left,right;
     *            字段类型——fieldtype,值2-NUMERIC,12—VARCHAR,91—DATE,,数据参数——pattern
     *            宽度——width
     * @param dataList
     *            List 数据集合
     * **/
    public void xls(String title,List t_headList, List dataList) {
       try {
            HttpServletResponse response = getResponse();
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(byteOut);
            jxl.write.WritableSheet ws = wwb.createSheet(title, 0);
            //  设置冻结单元格
            ws.setRowView(0, 25);// 行高
            // putRowHead(ws, 0, t_headList);// 在第一行插入表头信息
            WritableFont font10 = new WritableFont(WritableFont.TIMES, 10,
                    WritableFont.BOLD, false);
            WritableCellFormat hwcf = new WritableCellFormat(font10);
            hwcf.setWrap(true);//自动换行
            // 水平居中
            hwcf.setAlignment(jxl.format.Alignment.CENTRE);
            // 垂直居中
            hwcf.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            // 全边框
            hwcf.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
            for (int i = 0; t_headList!=null&&i < t_headList.size(); i++) {
                Map v = (Map) t_headList.get(i);
                String name = (String) v.get("FIELDNAME");
                java.math.BigDecimal width=(java.math.BigDecimal)v.get("WIDTH");
                Label cell = new Label(i, 0, "" + name, hwcf);
                CellFormat cf=cell.getCellFormat();
                ws.addCell(cell);
                if(width==null||"".equals(width))
                    ws.setColumnView(i, name.length() * 2 + 2); // 根据表头字数设置单元格 列, 宽
                else
                    ws.setColumnView(i, width.intValue());//根据规定的宽度设置宽度
            }

            // 9号 粗体
            WritableFont font9 = new WritableFont(WritableFont.TIMES, 9,
                    WritableFont.NO_BOLD, false);
            DecimalFormat df2 = (DecimalFormat) DecimalFormat.getInstance();// 格式化数字实例
           
            List list_wcf=new ArrayList();
            for (int k = 0; t_headList!=null&&k < t_headList.size(); k++) {
                Map map = (Map) t_headList.get(k);
                String align = (String) map.get("ALIGN");
                int fieldtype=Integer.parseInt(map.get("FIELDTYPE").toString());
                String pattern = (String) map.get("PATTERN");
                WritableCellFormat wcf =null;
                jxl.write.DateFormat df =null;
                jxl.write.NumberFormat nf =null;
                if(91 == fieldtype&&pattern!=null){
                    df=new jxl.write.DateFormat(pattern);
                    wcf=new WritableCellFormat(font9,df);
                }else if(fieldtype > 1 && fieldtype < 9 && fieldtype != 7&&pattern!=null){
                    nf=new jxl.write.NumberFormat(pattern);
                    wcf=new WritableCellFormat(font9,nf);
                }else
                    wcf=new WritableCellFormat(font9);
                wcf.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
                wcf.setWrap(true);
                // 全边框
                wcf.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
                if ("right".equals(align))
                    wcf.setAlignment(jxl.format.Alignment.RIGHT);
                else if("center".equals(align))
                    wcf.setAlignment(jxl.format.Alignment.CENTRE);
//                else if ("left".equals(align))
//                wcf.setAlignment(jxl.format.Alignment.LEFT);
               
                list_wcf.add(wcf);
            }
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> v = (Map) dataList.get(i);
                ws.setRowView(i + 1, 15);// 行高
                for (int k = 0; t_headList!=null&&k < t_headList.size(); k++) {
                    Map map = (Map) t_headList.get(k);
                    WritableCellFormat wcf = (WritableCellFormat)list_wcf.get(k);
                    String field = (String) map.get("FIELD");
                    int fieldtype=9;
                    if(map.get("FIELDTYPE")!=null)
                        fieldtype = Integer.parseInt(map.get("FIELDTYPE").toString());
                    String pattern = (String) map.get("PATTERN");
                    int p = field.trim().lastIndexOf(" ");
                    if (p > 0)
                        field = field.substring(p + 1, field.length());// 字段取别名
                    Object val = v.get(field);
                    if (91 == fieldtype && val != null && pattern!=null) {// 日期
                        try {
//                            System.out.println(val);
//                            val = getCurrentTime((Date) val, pattern);// 日期格式化输入样式
                            jxl.write.DateTime labelDTF = new jxl.write.DateTime(k, i + 1, (Date)val,wcf);
                            ws.addCell(labelDTF);
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("日期格式化失败!");
                            Label cell = new Label(k, i + 1, "日期格式化失败", wcf);
                            ws.addCell(cell);
                        }
                    }else if (fieldtype > 1 && fieldtype < 9 && fieldtype != 7) {// 数字类型{
                        if (val ==null || "".equals(val.toString()))    val="0.0";
                            try {
                                jxl.write.Number labelNF = new jxl.write.Number(k, i + 1, Double.valueOf(val.toString()), wcf); 
                                ws.addCell(labelNF);
                            } catch (Exception e) {
                                e.printStackTrace();
                                System.out.println("数字格式化失败!");
                                Label cell = new Label(k, i + 1, "数字格式化失败", wcf);
                                ws.addCell(cell);
                            }
                    }else{
                        if (val != null) {
                            Label cell = new Label(k, i + 1, val.toString(), wcf);
                            ws.addCell(cell);
                        } else {
                            Label cell = new Label(k, i + 1, null, wcf);
                            ws.addCell(cell);
                        }
                    }
                }
            }
            wwb.write();
            wwb.close();
            // 输出文件名字编码
            String agent = getRequest().getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE")) {
                title = java.net.URLEncoder.encode(title, "UTF-8").replace("+",
                        " ");
            } else if (null != agent && -1 != agent.indexOf("Firefox")) {
                title = new String(title.getBytes("UTF-8"), "iso8859-1");
            } else if (null != agent && -1 != agent.indexOf("Safari")) {
                title = java.net.URLEncoder.encode(title, "UTF-8").replace("+",
                        " ");
            }
            response.setContentType("application/xls");
            String exportname = title + "_"
                    + this.getCurrentTime(new Date(), "yyyy_MM_dd") + ".xls";
            response.addHeader("Content-Disposition", "attachment; filename=\""
                    + exportname + "\"");

            byte[] bytes = byteOut.toByteArray();
            response.setContentLength(bytes.length);
            ServletOutputStream sos = response.getOutputStream();
            sos.write(bytes, 0, bytes.length);
            sos.flush();
            sos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

配置表头数据库设计

 

URL    varchar2 (100)    请求地址        Action + '_' + method
Field    varchar2 (20)    字段代码       
FieldName    Nvarchar2(50)    字段名称    Null   
FieldType    Number(3)    字段类型    12    2-number,12- varchar2,91-Date
Align    varchar2 (10)    对齐方式    center    left,center,right
Pattern    varchar2 (10)    输出样式参数    Null    如:yyyy-mm-dd,#,###
Width    Number(3)    列宽度    Null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EasyExcel是阿里巴巴开源的一款Java库,用于简化Excel数据读写操作,特别适合高性能多sheet的导出。它的设计旨在提供易用性和性能优化,支持一次性处理多个工作表,并能处理大数据量。 以下是一个简单的EasyExcel多sheet导出Excel通用代码示例: ```java import com.alibaba.excel.EasyExcel; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.style.WriteCellStyle; import java.io.FileOutputStream; import java.util.List; import java.util.Map; public class ExcelExport { public static void main(String[] args) { // 数据源(这里假设是两个List,分别对应两个工作表) List<Map<String, Object>> sheet1Data = ...; List<Map<String, Object>> sheet2Data = ...; try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) { // 创建Excel写入对象,设置工作簿名和工作表信息 WriteAutoClose workbook = EasyExcel.write(outputStream, YourEntity.class) .build(); // 写入第一个工作表 workbook.write(sheet1Data, "Sheet1", new WriteSheet() { @Override public String getName() { return "Sheet1"; } }); // 设置第一个工作表的样式 workbook.getWriteSheetRegistry().get("Sheet1").setWriteCellStyle(new WriteCellStyle() { // 自定义样式配置 }); // 写入第二个工作表 workbook.write(sheet2Data, "Sheet2", new WriteSheet() { @Override public String getName() { return "Sheet2"; } }); // 关闭并写入文件 workbook.finish(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个例子中,你需要替换`YourEntity.class`为实际的数据实体类,`sheet1Data`和`sheet2Data`为你要写入的工作表数据。每个`WriteSheet`对象表示一个工作表,并且可以自定义工作表的名字和样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值