如何将asp.net gridview数据导出为excel ..? [英] How to export asp.net gridview data to excel..?
问题描述
我使用此代码将数据从gridview导出到excel ..
< asp:GridView ID = GridView1 runat = server AutoGenerateColumns = False EnableModelValidation = True
OnRowEditing = GridView1_RowEditing OnRowUpdating = GridView1_RowUpdating OnRowCommand = GridView1_RowCommand
OnRowCancelingEdit = GridView1_RowCancelingEdit >
<列>
< asp:TemplateField HeaderText = 产品名称 >
< itemtemplate>
< asp:Label ID = lblProductName runat = server Text = ' <%#Eval(ProductName)%>' >
< / itemtemplate >
< asp: TemplateField HeaderText = 数量 >
< itemtemplate>
< asp:Label ID = lblQty runat = server Text = ' <%#Eval(数量)%>' >
< / itemtemplate >
< edititemtemplate>
< asp:TextBox ID = txtQty runat = server Text = ' <%#Eval(数量)%>'宽度= 50px >
< / edititemtemplate >
< asp:TemplateField HeaderText = 价格 >
< itemtemplate>
< asp:标签ID = lblPrice runat = server Text = ' <%#Eval(Price)%>' >
< / itemtemplate >
< asp: TemplateField HeaderText = 总价格 >
< itemtemplate>
< asp:Label ID = lblTotalPrice runat = server Text = ' <%#Eval(总计)%>' >
< / itemtemplate >
< asp: TemplateField HeaderText = 编辑 >
< edititemtemplate>
< asp:LinkButton ID = lnkUpdate runat = server Text = 更新 CommandName = 更新
CommandArgument = ' <%#Eval(ProductID)%>' >
< asp:LinkButton ID = lnkCancel runat = server CommandName = 取消 Text = 取消
CommandArgument = ' <%#Eval(ProductID)%>' >
< / edititemtemplate >
< itemtemplate>
< asp:LinkButton ID = lblEditItem runat = server Text = 编辑 CommandName = 编辑 CommandArgument = ' <%#Eval(ProductID)%>' />
< / itemtemplate >
< asp:TemplateField HeaderText = 取消 >
< itemtemplate>
< asp:LinkButton ID = lblCancelItem runat = server Text = 取消 CommandArgument = ' <%#Eval(ProductID)%>'
OnClick = lblCancelItem_Click />
< / itemtemplate >
< / columns >
protected void BindData()
{
DataTable result =(DataTable)Session [ MyTable];
if (result.Rows.Count > 0 )
{
GridView1.DataSource = result;
GridView1.DataBind();
}
}
I use this code for exporting data to excel from gridview .. 这篇关于如何将asp.net gridview数据导出为excel ..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
< pre lang =c#> protected void Export2Excel()
{
< span class =code-keyword> try
{
this .GridView1.AllowPaging = 假跨度>;
此 .GridView1.AllowSorting = false ;
this .GridView1.EditIndex = -1;
// 让我们将数据绑定到GridView
此跨度> .BindData();
// 让我们输出GridView的HTML
Response.Clear ();
Response.ContentType = application / vnd.xls;
Response.AddHeader( content-disposition,
attachment; filename = MyList.xls);
Response.Charset = ;
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
GridView1.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
catch (例外exe)
{
throw exe;
}
}
但是当我执行这个当时我得到这个错误的方法
控制' ' GridView'的class =code-string> GridView1'
必须放置在一个带有runat = server的表单标签内。
i从网上获取此代码。
我哪里错了.... 感谢大家给我解决方案...
现在我得到了我的错误,我解决了它现在它工作得很好..
i添加了一个更新面板,所以当我删除我的更新面板相同的代码工作时我得到了这个错误没有错误..
试试这个链接..
http://www.as pdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-excel-or.html [ ^ ]
借助这个类,你可以在Excel中导出网格视图数据。只传递2个参数文件名和网格实例。
使用系统;
使用System.Collections.Generic;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControls;
使用System.IO;
使用iTextSharp.text.html;
使用iTextSharp.text.html.simpleparser;
使用iTextSharp.text;
使用iTextSharp.text.pdf;
///< summary>
/// ExcelExport的摘要说明
///< /摘要>
公共类ExcelExpor t $ / b
$
public static void Export(string fileName,GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
content-disposition,string.Format(attachment ; filename = {0},fileName));
HttpContext.Current.Response.ContentType =application / ms-excel;
using(StringWriter sw = new StringWriter())
{
using(HtmlTextWriter htw = new HtmlTextWriter(sw))
{
//创建一个包含网格的表
表table = new Table();
//包括网格线设置
table.GridLines = gv.GridLines;
//将标题行添加到表中
if(gv.HeaderRow!= null)
{
ExcelExport.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
} < br $>
//将每个数据行添加到表中
foreach(gv.Rows中的GridViewRow行)
{
ExcelExport.PrepareControlForExport(row);
table.Rows.Add(row);
}
//将页脚行添加到表格
if(gv.FooterRow!= null)
{
ExcelExport.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
//将表格渲染到htmlwriter中
table.RenderControl(htw);
//将htmlwriter渲染到响应中
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response .End();
}
}
}
// /< summary>
///用文字替换任何包含的控件
///< / summary>
// /< param name =control>< / param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0;我< control.Controls.Count; i ++)
{
控制电流= control.Controls [i];
if(当前是LinkButton)
{
control.Controls.Remove(当前);
control.Controls.AddAt(我,新的LiteralControl((当前
作为LinkButton )。文本));
}
否则if(当前是ImageButton)
{
control.Controls 。删除(当前);
control.Controls.AddAt(我,新的LiteralControl((当前
作为ImageButton).AlternateText));
}
否则if(当前是HyperLink)
{
control.Controls.Remove(当前);
control.Controls.AddAt(i,new LiteralControl((当前
作为HyperLink).Text));
}
else if(当前是DropDownList)
{
control.Controls.Remove(当前);
control.Controls.AddAt(i,new LiteralControl((当前
作为DropDownList).SelectedItem.Text));
}
否则if(当前是CheckBox)
{
control.Controls.Remove(当前);
control.Controls.AddAt(我,新的LiteralControl((当前
作为CheckBox)。检查? 真:假));
}
if(current.HasControls())
{
ExcelExport.PrepareControlForExport(当前);
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
<columns>
<asp:TemplateField HeaderText="Product Name">
<itemtemplate>
<asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>'>
</itemtemplate>
<asp:TemplateField HeaderText="Qty">
<itemtemplate>
<asp:Label ID="lblQty" runat="server" Text='<%# Eval("Qty") %>'>
</itemtemplate>
<edititemtemplate>
<asp:TextBox ID="txtQty" runat="server" Text='<%# Eval("Qty") %>' Width="50px">
</edititemtemplate>
<asp:TemplateField HeaderText="Price">
<itemtemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price") %>'>
</itemtemplate>
<asp:TemplateField HeaderText="Total Price">
<itemtemplate>
<asp:Label ID="lblTotalPrice" runat="server" Text='<%# Eval("Total") %>'>
</itemtemplate>
<asp:TemplateField HeaderText="Edit">
<edititemtemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update"
CommandArgument='<%# Eval("ProductID") %>'>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" Text="Cancel"
CommandArgument='<%# Eval("ProductID") %>'>
</edititemtemplate>
<itemtemplate>
<asp:LinkButton ID="lblEditItem" runat="server" Text="Edit" CommandName="Edit" CommandArgument='<%# Eval("ProductID") %>' />
</itemtemplate>
<asp:TemplateField HeaderText="Cancel">
<itemtemplate>
<asp:LinkButton ID="lblCancelItem" runat="server" Text="Cancel" CommandArgument='<%# Eval("ProductID") %>'
OnClick="lblCancelItem_Click" />
</itemtemplate>
</columns>
protected void BindData()
{
DataTable result = (DataTable)Session["MyTable"];
if (result.Rows.Count > 0)
{
GridView1.DataSource = result;
GridView1.DataBind();
}
}
protected void Export2Excel()
{
try
{
this.GridView1.AllowPaging = false;
this.GridView1.AllowSorting = false;
this.GridView1.EditIndex = -1;
// Let's bind data to GridView
this.BindData();
// Let's output HTML of GridView
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition",
"attachment;filename=MyList.xls");
Response.Charset = "";
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
GridView1.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
catch (Exception exe)
{
throw exe;
}
}
But when i execute this method at that time i got this error
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
i got this code from web.
Where i am wrong....Thanks for all of you to give me solutions...
Now i got my mistake and i solve it now it work perfectly..
i have added a update panel so i got that error when i remove my update panel the same code work without error..Try this link..
http://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-excel-or.html[^]With help of this class u can export grid view data in Excel.Only pass 2 parameter file name and grid instance.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text;
using iTextSharp.text.pdf;
/// <summary>
/// Summary description for ExcelExport
/// </summary>
public class ExcelExport
{
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment;filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
// include the gridline settings
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
ExcelExport.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
ExcelExport.PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
ExcelExport.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name="control"></param>
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current
as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current
as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current
as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current
as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current
as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
ExcelExport.PrepareControlForExport(current);
}
}
}
}