且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#从Gridview导出到Excel

更新时间:2023-10-16 09:12:52

嗨Mahesh

在我的代码中编写一个查询,用于选择所需的值并将其导出到excel。

  string  str =  您的查询; 
ds = da.fill_data(str);
DataTable dt = new DataTable();
dt = ds.Tables [ 0 ];
string attachment = attachment; filename = ABC.xls跨度>;
Response.ClearContent();
Response.AddHeader( content-disposition,附件);
Response.ContentType = application / vnd.ms-excel;
string tab = ;
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = \t;
}
Response.Write( \ n);
int i;
foreach (DataRow dr in dt.Rows)
{
tab = ;
for (i = 0 ; i < ; dt.Columns.Count; i ++)
{
Response.Write(tab + dr [i] .ToString());
tab = \t;
}
Response.Write( \ n);
}
Response.End();





作为答案,如果它可以帮助你。


有类似的文章

将DataGrid导出到Excel, Word和文本文件 [ ^ ]





或者你可以使用EPPLUS

你可以制作一个通用的方法来检索数据源

并将其用于网格生成和excel生成

EPPLUS示例:

http:// epplus.codeplex.com/wikipage?title=WebapplicationExample[^]



i认为它非常容易使用,并且不太容易出现兼容性错误,从xml /创建excel HTML

hi
when export to excel the excel file contains the hidden column from gridview.

i explain it deeply.

In GridView I hide the 3rd column and export to excel.

in excel file I need the "C" column with hidden.

Hi Mahesh
In my code write a query for picking values which you want and export them to excel.
string str = "your Query";
           ds = da.fill_data(str);
           DataTable dt = new DataTable();
           dt = ds.Tables[0];
           string attachment = "attachment; filename=ABC.xls";
           Response.ClearContent();
           Response.AddHeader("content-disposition", attachment);
           Response.ContentType = "application/vnd.ms-excel";
           string tab = "";
           foreach (DataColumn dc in dt.Columns)
           {
               Response.Write(tab + dc.ColumnName);
               tab = "\t";
           }
           Response.Write("\n");
           int i;
           foreach (DataRow dr in dt.Rows)
           {
               tab = "";
               for (i = 0; i < dt.Columns.Count; i++)
               {
                   Response.Write(tab + dr[i].ToString());
                   tab = "\t";
               }
               Response.Write("\n");
           }
           Response.End();



make as answer if it helps You.


there are articles like that
Exporting DataGrid to Excel, Word and Text Files[^]


or you can use EPPLUS
you can make a generic method to retrieve the datasource
and use it both for grid generation and excel generation
EPPLUS Example :
http://epplus.codeplex.com/wikipage?title=WebapplicationExample[^]

i think it is quite symple to use and less prone to compatibility error that creating excel from the xml/html