Studio for ASP.NET Wijmo: 导出 C1GridView 到 Excel 文件

发布时间:2014/05/16 00:05 发布者:iceman

返回博客中心

C1GridView 表格控件用于在前台展示数据,最近有用户提出把 C1GridView 导出到 Excel 文件的需求,考虑到还会有其他用户有此需求,所以分享给大家浏览,希望能对广大用户有所帮助。

C1GridView 本身不支持导出到 Excel 文件,在本篇文章中将分别介绍如何通过自定义方法把 C1GridView以 Excel 形式导出到客户端和服务器端。

导出到客户端,通过 HtmlTextWriter 来实现,代码如下:

        protected void Button1_Click(object sender, EventArgs e)
        {
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite=new HtmlTextWriter(stringWrite);
            C1GridView dg=new C1GridView();
            dg=this.C1GridView2;
            dg.HeaderStyle.ForeColor = System.Drawing.Color.Black;
            dg.RowStyle.ForeColor = System.Drawing.Color.Black;
 
            dg.AllowSorting = false;
            dg.AllowPaging = false;
            dg.AllowCustomPaging = false;
            Control parent=dg.Parent;
            //parent.Controls.Remove(dg);
 
            dg.RenderControl(htmlWrite);
 
            parent.Controls.Add(dg);
            string content = stringWrite.ToString();
            HttpResponse response=this.Response;
            response.Clear();
            response.Buffer = true;
            response.Charset = "";
            response.ContentType = "application/vnd.ms-excel";
            response.ContentEncoding = new UTF8Encoding();
            response.Write(content);
            response.End();
        }

 

导出到服务器端,需要结合 Studio for ASP.NET Wijmo 套包中的另一款插件 C1XLBook 实现,主要思路是创建 C1XLBook 后,遍历 C1GridView 的单元格值,赋值给 C1XLBook 单元格。代码如下:

C1.C1Excel.C1XLBook excelBook = new C1.C1Excel.C1XLBook();
            excelBook.Sheets.Add("C1GridView");
            C1.C1Excel.XLSheet sheet = excelBook.Sheets[0];
            int rowCount = this.C1GridView2.Rows.Count;
            int colCount = this.C1GridView2.Columns.Count;
            for (int i = 0; i < rowCount; i++)
			{
                C1.C1Excel.XLRow row=new C1.C1Excel.XLRow();
                sheet.Rows.Add(row);
			}
            
            for (int i = 0; i < colCount; i++)
			{
                C1.C1Excel.XLColumn col=new C1.C1Excel.XLColumn();
                sheet.Columns.Add(col);
			}
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < colCount; j++)
                {
                    string text = this.C1GridView2.Rows[i].Cells[j].Text;
                    sheet[i, j].SetValue(text, null);
                }
            }
            excelBook.Save(this.Server.MapPath("test.xls"));
        }

 

可以下载 Demo 进行测试:

VS2013 + .NET 4.0 + Studio for ASP.NET Wijmo 2014V1


关于葡萄城

赋能开发者!葡萄城是专业的集开发工具、商业智能解决方案、低代码开发平台于一身的软件和服务提供商,为超过 75% 的全球财富 500 强企业提供服务。葡萄城专注控件软件领域30年,希望通过模块化的开发控件、灵活的低代码应用开发平台等一系列开发工具、解决方案和服务,帮助开发者快速响应复杂多变的业务需求,最大程度地发挥开发者的才智和潜能,让开发者的 IT 人生更从容更美好。

了解详情,请访问葡萄城官网