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