匯出Ext.grid.Panel到excel

來源:互聯網
上載者:User

1.用戶端定義,基本的想法是form提交表格頭定義,資料,以json方式傳輸

 Ext.grid.Panel.addMembers({    exportExcel:function(options){       if(!Ext.isDefined(options)){options={}};       options.name = options.name || '未命名';       //這兒有一個約定,以time或date結尾的屬性是時間類型       var cms=Ext.Array.map(this.columns,function(item){          if(Ext.String.endsWith(item.dataIndex,'time',true) || Ext.String.endsWith(item.dataIndex,'date',true)){            return {dataIndex:item.dataIndex,text:item.text,datatype:'DateTime',format:'yyyy-MM-dd HH:mm:ss'}          }          else{            return {dataIndex:item.dataIndex,text:item.text}          }       });       var data=Ext.Array.map(this.store.getRange(),function(item){           var d={};           for(var index=0;index<cms.length;index++){              var attName=cms[index].dataIndex              d[attName]=item.data[attName]           }          return d;       });       var form = Ext.create('Ext.form.Panel', {url:'/system/export/excel'                ,standardSubmit: true                ,frame:true                ,items:[{xtype:'hiddenfield',name:'cms',value:Ext.JSON.encodeValue(cms)}                ,{xtype:'hiddenfield',name:'data',value:Ext.JSON.encodeValue(data)}                ,{xtype:'hiddenfield',name:'fileName',value:options.name+ '.xls'}                ]            });       form.getForm().submit();    }  });

 

 2.調用執行個體 this.gridPn.exportExcel({name:this.title});3.現在的工作轉到了服務端.操作excel的方法比較多,我個人喜歡myxls,因為資料是json傳過來的,建議使用json.net,有了這兩樣好工具.只需要簡單的封裝一下就可以完成一般性的任務了.
using System;  using System.Collections.Generic;  using System.Linq;  using System.Web;  using System.Web.Mvc;  using System.IO;  using System.Text;  using Newtonsoft.Json.Linq;  using org.in2bits.MyXls;    namespace CJRApp2.Web.Controllers  {      public class ExportController : Controller      {                  // private DateTime baseDT = new DateTime(1970, 1, 1, 8, 0, 0);            private void addCell(XlsDocument doc, JToken r, JToken c, Cells cells, int rowIndex, int cellIndex)          {              string cName = c["dataIndex"].ToString();                if (c["datatype"] == null)              {                    JValue jv = r[cName] as JValue;                  if (jv != null && jv.Value != null)                  {                      switch (jv.Type)                      {                          case JTokenType.Float:                              cells.Add(rowIndex, cellIndex, jv.ToObject<decimal>());                              break;                          case JTokenType.Integer:                              cells.Add(rowIndex, cellIndex, jv.ToObject<int>());                              break;                          default:                              cells.Add(rowIndex, cellIndex, jv.ToString());                              break;                        }                    }                  }              else if (c["datatype"].ToString() == "DateTime")              {                    DateTime dt;                  if (r[cName] != null && DateTime.TryParse(r[cName].ToString(),out dt))                  {                      string format = "yyyy-MM-dd HH:mm:ss";                      if (c["format"] != null)                      {                          format = c["format"].ToString();                      }                      XF xf = doc.NewXF();                      xf.Format = format;                      Cell cell = cells.Add(rowIndex, cellIndex, dt, xf);                    }              }          }              [HttpPost]          [ValidateInput(false)]          public ActionResult excel(string cms, string data, string title = "標題", string fileName = "export.xls")          {              string json = "{\"data\":" + data + ",\"cms\":" + cms + "}";              JObject jsonObj = JObject.Parse(json);              JToken cmsObj = jsonObj["cms"];              JToken dataObj = jsonObj["data"];              List<JToken> cmss = cmsObj.ToList();              List<JToken> datas = dataObj.ToList();                  if (HttpContext.Request.UserAgent.IndexOf("MSIE") != -1)              {                  fileName = HttpContext.Server.UrlEncode(fileName);              }              XlsDocument doc = new XlsDocument();              Worksheet sheet = doc.Workbook.Worksheets.Add(title);              Cells cells = sheet.Cells;                int rowIndex = 1;              int cellIndex = 0;              bool addrow = false;              foreach (JToken t in cmss)              {                  cellIndex++;                  Cell cell = cells.Add(rowIndex, cellIndex, t["text"].ToString());                    if (t["columns"] != null)                  {                      addrow = true;                      int c2Index = 0;                      foreach (JToken c2 in t["columns"])                      {                          cells.Add(rowIndex + 1, cellIndex + c2Index, c2["text"].ToString());                          c2Index++;                      }                      cellIndex += t["columns"].Count() - 1;                      //sheet.AddMergeArea                  }                  }              if (addrow) { rowIndex++; }              foreach (JToken r in datas)              {                  rowIndex++;                  cellIndex = 0;                  foreach (JToken c in cmss)                  {                      cellIndex++;                      if (c["columns"] != null)                      {                          foreach (JToken cc in c["columns"])                          {                              addCell(doc, r, cc, cells, rowIndex, cellIndex++);                          }                          cellIndex--;                      }                      else                      {                          addCell(doc, r, c, cells, rowIndex, cellIndex);                      }                        }              }                return this.File(doc.Bytes.ByteArray, "application/vnd.ms-excel", fileName);            }      }  }  

 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.