extjs4.2导出excel表格

本文介绍了一种使用Java实现的导出Excel表格及图表的方法,包括生成Excel文件、图表文件,以及通过Ajax请求实现文件下载的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
**1、要有个java类,类里要有生成excle方法,下载文件,生成临时文件方法,获取文件方法。在ajax请求成功时,调用获取getExelcFile方法
2.要有个js导出数据的方法**
开启民工视角:
ExportExcelAction .java

package com.geoway.platform.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ezmorph.bean.MorphDynaBean;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.geoway.common.util.StringUtility;
import com.geoway.common.util.ZipCompressorByAnt;
import com.geoway.core.action.BaseAction;

@Controller("exportExcelAction")
@Scope("prototype")
public class ExportExcelAction extends BaseAction {

    private final Logger logger = Logger.getLogger(ExportExcelAction.class);    


    public void export() throws Exception{
        HttpServletRequest request = ServletActionContext.getRequest();

        String exportData = request.getParameter("exportData");
        String uuid = StringUtility.getUUID();      

        JSONObject jSONObject = JSONObject.fromObject(exportData);

        JSONObject excelObject = jSONObject.getJSONObject("excelData");

        String fileName = (String) excelObject.get("name");
        if(fileName ==null || fileName ==""){
            throw new Exception("统计结果为空,不可导出!");
        }
        //临时文件路径初始化
        String tmpDirName = this.getTmpDirName(uuid);
        //生成EXCEL
        this.createExcelFile(excelObject, tmpDirName);

        String filePath = this.createExcelFile(excelObject, tmpDirName).toString();

//      download(this.createExcelFile(excelObject, tmpDirName));


        JSONArray jSONArray = jSONObject.getJSONArray("chartsData");
        List<MorphDynaBean> i =  (List<MorphDynaBean>) JSONArray.toCollection(jSONArray);

        //生成图表
        for(MorphDynaBean bean : i){
            this.createChart(bean, tmpDirName);
        }
        //需求改变,要下载xls格式,压缩功能先不用
//      String zip = tmpDirName.substring(0,tmpDirName.length()-1) + ".zip";
//      ZipCompressorByAnt zca = new ZipCompressorByAnt(zip);   //apache ant方式压缩
//      zca.compress(tmpDirName);       
        this.sendJSONWeb("{success:true,uuid:'" + uuid + "'}");
    }



    public void getExcelFile() throws UnsupportedEncodingException{
        HttpServletRequest request = ServletActionContext.getRequest();
        String exportData = request.getParameter("exportData");
        String uuid = request.getParameter("uuid");
        //获得并拼接压缩包的名字
        String tempName = request.getParameter("name").toString();
        String zipName=java.net.URLDecoder.decode(tempName,"UTF-8");
        zipName = zipName.replaceAll(" ", "") + this.getCurrentDateTime();      

        //临时文件路径初始化
        String tmpDirName = this.getTmpDirName(uuid);

        String downPath = tmpDirName.substring(0,tmpDirName.length()-1) + "\\统计数据.xls"; 
        //D:\temp\73292191\统计数据.xls
        //D:/temp\73292191\统计数据.xls

        File file = new File(downPath);

        ServletOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);

            HttpServletResponse response = ServletActionContext.getResponse();

            response.reset();

            response.setContentType("zip/*");
            String serverName = request.getServerName();
            String Location = "http://" + serverName + "//";
            response.setHeader("Content-Location", Location);
            response.setHeader("Content-Disposition","attachment;filename="+new String((zipName.trim()).getBytes("gb2312"), "ISO8859-1")+".xls");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 获得临时路径
     * @param uuid
     * @return
     */
    private String getTmpDirName(String uuid){
        String tempSavePath = "D:/temp";

//      try {
//          tempSavePath = PropertiesUtility.getInstance().getProperties("appconfigZlgl", "app.temp_export_path");
//      } catch (CommonException e) {
//          logger.error(e.getMessage());
//          throw new ActionException("没有配置导出临时空间");
//      }
//      if(tempSavePath == null){
//          logger.error("没有配置导出临时空间");
//          throw new ActionException("没有配置导出临时空间");
//      }
        //创建临时文件夹
        String dir = tempSavePath+File.separator+uuid+File.separator;

        File file = new File(dir);   
        if(!file.exists()){
            file.mkdirs();   
        }
        return dir;

    }

    private File createChart(MorphDynaBean bean,String tmpDirName) throws Exception{

        String svgString = "";
        String fileName = "";
        try{
            svgString = (String) bean.get("data");
            fileName = (String) bean.get("name");
        }catch(Exception e){
            e.getStackTrace();
            throw new Exception("统计结果为空,不可导出!");

        }



        fileName = tmpDirName + fileName + ".jpg";

        File file = new File(fileName);

        OutputStream out = new FileOutputStream(file);

        JPEGTranscoder t = new JPEGTranscoder();

        t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,new Float(.8));

        TranscoderInput input = new TranscoderInput(new StringReader(svgString));


        try {
            TranscoderOutput output = new TranscoderOutput(out);
            t.transcode(input, output);
            out.flush();
            out.close();
            return file;
       }catch (Exception e){
            out.flush();
            out.close();
            e.printStackTrace();
            return file;
        }
    }

    **ExportExcel.js**
    /**
     * 导出EXCEL
     * @param excelObject
     * @param tmpDirName
     * @return
     * @throws IOException
     */
    private File createExcelFile(JSONObject excelObject,String tmpDirName) throws IOException{
        String fileName = (String) excelObject.get("name");
        String data = (String)excelObject.get("data");

        System.out.println(data);

        fileName = tmpDirName + fileName + ".xls";

        File file = new File(fileName);

        BufferedOutputStream buff = new BufferedOutputStream(new FileOutputStream(file)); ; 

        Writer out = new OutputStreamWriter(buff, "UTF-8"); 

        out.write(data);   
        out.close();   
        buff.close();   
        buff.close();

        return file;

    }

    public String getCurrentDateTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = df.format(new Date());
        return s;
    }


}

Ext.define('ExportExcel', {
    /**
     * 导出
     * grid实例
     * charts实例数组
     */
    //TODO 放到别的包下
    exprotData:function(grid,charts){
        var statisticsExport = getRootPath()+'/platform/exportExportExcelAction.action';
        var statisticsGetFile = getRootPath()+'/platform/getExcelFileExportExcelAction.action';
//      var doStatistics = _ctxPath+'/exceptionCheck/doStatisticsStatisticsAction.action';

        var exportData = {};
        exportData['excelData'] =  grid.getExportData();
        var chartsData = [];

        for(var i = 0;i < charts.length ; i ++){
            chartsData.push(charts[i].items.items[0].getExportData());
        }

        exportData.chartsData = chartsData;
        var postObject = {};
        var name = exportData.excelData.name;
        name = encodeURI(encodeURI(name));
        postObject.exportData = Ext.encode(exportData);
        Ext.Ajax.request({
               url: statisticsExport,
               method : 'post',
               scope : this,
               timeout : 60000,
               params: postObject,
               success: function(response){
                   var res = Ext.decode(response.responseText);
                   if(res.success == true){
                        var url = statisticsGetFile + "?uuid="+res.uuid+"&name="+name;
                        window.open(url);
                   }
               }
            });
    }
});

前台调用ExportExcel方法:

var exportExcelButton = Ext.create('Ext.button.Button',{
            hidden : true,
            cls:'.mybutton',
            text: '<span style="font-size:13px; font-weight:normal">保存</span>',
            margin: '6 70 0 10',//(top, right, bottom, left)
            scope:this,
            handler: function() {
                var exportExcel = Ext.create('ExportExcel',{});
                exportExcel.exprotData(this.grid,'');
            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值