zoukankan      html  css  js  c++  java
  • 导出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);
    
            }
        }
    }



  • 相关阅读:
    SynEdit(Delphi XE7)的安装和基本使用
    uniConnection断线重联(tag属性颇有深意,这样就可以在某些情况下,不用继承实现新控件就可以达到自己的目的)
    CheckSynchronize实现的不必要的复杂
    Delphi中Indy 10的安装和老版本的卸载
    JavaScript2
    C#中使用REDIS
    jQuery多文件
    Node+Express+MongoDB + Socket.io搭建实时聊天应用
    jQuery选取和操纵元素的特点
    Mvc 6 中创建 Web Api
  • 原文地址:https://www.cnblogs.com/james1207/p/3320012.html
Copyright © 2011-2022 走看看