导出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);

        }
    }
}


 


 

转载于:https://www.cnblogs.com/james1207/p/3320012.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值