標籤:style blog http color os io 檔案 資料
Extjs — Grid資料匯出成Excel
最近因為項目問題,需要解決Extjs匯出成Excel的問題。
下面簡單描述這個問題解決的步驟如下:
1、先在js檔案裡寫了一個button的handler事件,通過點擊按鈕,來實現調用ExportExcel(GridPanel,{store:null, title: ‘ ‘})
ExportExcel方法的源碼如下:
/** Execl匯出方法 **/ function ExportExcel(gridPanel, config) { if (gridPanel) { var tmpStore = gridPanel.getStore(); var tmpExportContent = ‘‘; //以下處理分頁grid資料匯出的問題,從伺服器中擷取所有資料,需要考慮效能 var tmpParam = Ext.ux.clone(tmpStore.lastOptions); //此處複製了原網格資料來源的參數資訊 if (tmpParam && tmpParam.params) { delete (tmpParam.params[tmpStore.paramNames.start]); //刪除分頁參數 delete (tmpParam.params[tmpStore.paramNames.limit]); } var tmpAllStore = new Ext.data.GroupingStore({//重新定義一個資料來源 proxy: tmpStore.proxy, reader: tmpStore.reader }); tmpAllStore.on(‘load‘, function (store) { config.store = store; tmpExportContent = gridPanel.getExcelXml(false, config); //此方法用到了一中的擴充 if (Ext.isIE || Ext.isSafari || Ext.isSafari2 || Ext.isSafari3) {//在這幾種瀏覽器中才需要,IE8測試不能直接下載了 if (!Ext.fly(‘frmDummy‘)) { var frm = document.createElement(‘form‘); frm.id = ‘frmDummy‘; frm.name = id; frm.className = ‘x-hidden‘; document.body.appendChild(frm); } Ext.Ajax.request({ //將產生的xml發送到伺服器端,需特別注意這個頁面的地址 url: ‘GridToExcel.aspx‘, method: ‘POST‘, form: Ext.fly(‘frmDummy‘), callback: function (o, s, r) { //alert(r.responseText); }, isUpload: true, params: { ExportContent: tmpExportContent, ExportFile: gridPanel.id + ‘.xls‘ } }); } else { document.location = ‘data:application/vnd.ms-excel;base64,‘ + Base64.encode(tmpExportContent); } }); tmpAllStore.load(tmpParam); //擷取所有資料 }};
同時需要在引用了上面js檔案的 html檔案/aspx檔案裡 再引用一個GridToExecl.js檔案,因為代碼太多了,所以我把它上傳了,就不貼代碼了。
GridToExecl.js
2、GridToExcel.aspx頁面的相關代碼:
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridToExecl.aspx.cs" Inherits="GridToExecl" ValidateRequest="false" %> //ValidateRequest = "false"非常重要,缺少它,IE系列瀏覽器不能正常匯出
後台:
public partial class GridToExcel : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request["ExportContent"] != "") { string tmpFileName = "excel.xls"; string tmpContent = Request["ExportContent"];//擷取傳遞上來的檔案內容 if (Request["ExportFile"] != "") { tmpFileName = Request["ExportFile"];//擷取傳遞上來的檔案名稱 tmpFileName = System.Web.HttpUtility.UrlEncode(Request.ContentEncoding.GetBytes(tmpFileName));//處理中文檔案名稱的情況 } Response.Write("&lt;script&gt;document.close();&lt;/script&gt;"); Response.Clear(); Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=\"" + tmpFileName + "\""); Response.Charset = ""; this.EnableViewState = false; System.IO.StringWriter tmpSW = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter tmpHTW = new System.Web.UI.HtmlTextWriter(tmpSW); tmpHTW.WriteLine(tmpContent); Response.Write(tmpSW.ToString()); Response.End(); } } }