Java导出excel文件

前端js

packageId = encodeURI(encodeURI(packageId));//IE浏览器URL路径拼接中文访问报错问题

$(".download").click(function () {

var queryParams = {};

var url = layui.common.umsBaseURL + 'diff/dataDownLoad?packageId=' + packageId;

var xhr;

if(window.XMLHttpRequest){

        xhr = new XMLHttpRequest();

}else if(window.ActiveXObject){

         try{

                  xhr = new ActiveXObject('Msxml2.XMLHTTP');

        }catch(e){

                try{

                  xhr = new ActiveXObject('Microsoft.XMLHTTP');

                }catch(e){

                  return "";

                }}

}

else{

        return "";

}

xhr.open("GET",url,true);

xhr.responseType = "arraybuffer";//解决导出excel乱码问题,不能写在open之前,否则不支持IE浏览器

xhr.onload = function(){

        var blob = new  Blob([this.resonse],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});

        if(blob.size<1){

                layer.msg("报表导出失败!");

               return;

        }

        if(window.navigator.msSaveOrOpenBlob){//IE浏览器

                window.navigator.msSaveBlob(blob,package.trim() + "报表.xls");

        }else{//其他浏览器

                var alink = document.createElement("a");

                alink.style.display = "none";

                alink.href = window.URL.createObjectURL(blob);

                alink.download = package.trim() + "报表.xls";

                document.body.appendchild(alink);

                alink.click();

                document.body.removeChild(alink);

                return;

        }       

};

 xhr.setRequestHeader("Access-token",sessionStorage.getItem("token"));

xhr.setRequestHeader("Content-Type","application/json");

xhr.send(JSON.stringify(queryParams));

});

后台

public void dataload(data,response){

        HSSFWorkbook workbook = new HSSFWorkbook ();//创建excel对象

       try{

              String packageId= URLDecoder.decode(data.getPackageId(),"utf-8");//接受并转译URL路径中的中文字符

               data.setPackageId(packageId);

               //用于导出的数据集合

               List<BO>  dataset = diffMapper.dataDonLoad(data);

               OutputStream output = null;

               //excel导出工具类

               ExportExcel<BO> ex = new ExportExcel<>();

               //导出的标题列

               String[] headers = {"标题1","标题2","标题3","标题4"};

               output = response.getOutputStream();

               response.reset();//清空缓存

               String fileName = "报表.xls";

               response.addHeader(name:"Content-disposition",value:"attachmnet;filename=" + new  String(fileName.getBytes(), charserName:"utf-8"));//定义浏览器相应表头

               response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheet.sheet");//定义下载的类型

               workbook = ex.exportExcel(workbook,null,headers,dataset,fileName);//导出到Excel

               try{

                              workbook.write(output);

               }catch(IOException e){

                              e.printStackTrace();

               }

               output.close();

               log.info("报表导出成功");

       }catch(FileNotFoundException e){

                e.printStackTrace();

       }catch(IOException e){

                              e.printStackTrace();

        }

}

public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern,HSSFWorkbook workbook)  
    {  
        // 声明一个工作薄   生成一个表格  
        HSSFSheet sheet = workbook.getSheet(title);
        // 设置表格默认列宽度为15个字节  
        sheet.setDefaultColumnWidth((short) 15);  
        // 生成一个样式  
        HSSFCellStyle style = workbook.createCellStyle();  
        // 设置这些样式  
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        // 生成一个字体  
        HSSFFont font = workbook.createFont();  
        font.setColor(HSSFColor.VIOLET.index);  
        font.setFontHeightInPoints((short) 12);  
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        // 把字体应用到当前的样式  
        style.setFont(font);  
        // 生成并设置另一个样式  
        HSSFCellStyle style2 = workbook.createCellStyle();  
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);  
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
        // 生成另一个字体  
        HSSFFont font2 = workbook.createFont();  
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
        // 把字体应用到当前的样式  
        style2.setFont(font2);  
        // 声明一个画图的顶级管理器  
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();  
        // 定义注释的大小和位置,详见文档  
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));  
        // 设置注释内容  
        comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));  
        // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.  
        comment.setAuthor("leno");  

        // 产生表格标题行  
        HSSFRow row = sheet.createRow(0);  
        for (short i = 0; i < headers.length; i++)  
        {  
            HSSFCell cell = row.createCell(i);  
            cell.setCellStyle(style);  
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
            cell.setCellValue(text);  
        }  
        // 遍历集合数据,产生数据行  
        Iterator<T> it = dataset.iterator();  
        int index = 0;  
        while (it.hasNext())  
        {  
            index++;  
            row = sheet.createRow(index);  
            T t = (T) it.next();  
            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值  
            Field[] fields = t.getClass().getDeclaredFields();  
            for (short i = 0; i < fields.length; i++)  
            {  
                HSSFCell cell = row.createCell(i);  
                cell.setCellStyle(style2);  
                Field field = fields[i];  
                String fieldName = field.getName();  
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);  
                try  
                {  
                    Class tCls = t.getClass();  
                    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});  
                    Object value = getMethod.invoke(t, new Object[] {});  
                    // 判断值的类型后进行强制类型转换  
                    String textValue = null;  
                     
                    // 其它数据类型都当作字符串简单处理  
                    textValue = value == null? "": value.toString();  
                    
                    // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成  
                    if (textValue != null)  
                    {  
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
                        Matcher matcher = p.matcher(textValue);  
                        if (matcher.matches())  
                        {  
                            // 是数字当作double处理  
                            cell.setCellValue(Double.parseDouble(textValue));  
                        }  
                        else  
                        {  
                            HSSFRichTextString richString = new HSSFRichTextString(textValue);  
                            HSSFFont font3 = workbook.createFont();  
                            font3.setColor(HSSFColor.BLUE.index);  
                            richString.applyFont(font3);  
                            cell.setCellValue(richString);  
                        }  
                    }  
                }  
                catch (SecurityException e)  
                {  
                    e.printStackTrace();  
                }  
                catch (NoSuchMethodException e)  
                {  
                    e.printStackTrace();  
                }  
                catch (IllegalArgumentException e)  
                {  
                    e.printStackTrace();  
                }  
                catch (IllegalAccessException e)  
                {  
                    e.printStackTrace();  
                }  
                catch (InvocationTargetException e)  
                {  
                    e.printStackTrace();  
                }  
                finally  
                {  
                    // 清理资源  
                }  
            }  
        }  
    } 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值