当前位置:软件学习 > Excel >>

导出Ext.grid.Panel到excel

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);  
  
        }  
    }  
}  

 


补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,