1. 程式人生 > >extjs4.2匯出excel表格

extjs4.2匯出excel表格

思路:
**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,'');
            }
        });