急求一份将DataGrid中的数据导入到Excel

xuqingaisensen 2006-10-26 06:22:43
哪位大哥可以给我一份将DataGrid中的数据导入到Excel表格中的代码,先谢谢拉!
最好是可以加些注释的,再次深深感谢了!
...全文
192 15 打赏 收藏 举报
写回复
15 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
nimeide1234567890 2006-12-16
  • 打赏
  • 举报
回复
<asp:Button id="Button8" runat="server" Text="本頁面所有內容轉到EXCEL" Height="24px"></asp:Button>


private void ExportDataGrid2(string FileType, string FileName) //植DataGrid絳堤
{
Response.Clear();
Response.Buffer= true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" +HttpUtility.UrlEncode(FileName,Encoding.UTF8).ToString());
Response.ContentType = FileType;
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
this.EnableViewState =false;
System.IO.StringWriter tw = new StringWriter();
System.Web.UI.HtmlTextWriter hw =new HtmlTextWriter(tw);
MyList.RenderControl(hw); //注:MyList.RenderControl(hw); //只转数据,但MyList里有<asp:CheckBox id="selected" runat="server"></asp:CheckBox>就出错
//this.RenderControl(hw); //按钮等也转出来了

Response.Write(tw.ToString());
Response.End();
}


private void Button8_Click(object sender, System.EventArgs e)
{
//Save("application/ms-excel", "Excel.xls"); //絳善Excel
//ExportDataGrid("application/ms-excel", "Excel.xls"); //絳善Excel
ExportDataGrid2("application/ms-excel", "Excel.xls"); //絳善Excel
}
nimeide1234567890 2006-12-16
  • 打赏
  • 举报
回复
<%@ Page language="c#" Src="excel.cs" AutoEventWireup="false" Inherits="DataGrid_import_WordExcel.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>OutPutExcel</title>
</HEAD>
<link rel="stylesheet" href="Style.css" type="text/css">
<body>
<form id="Form1" method="post" runat="server">
<table width="170%"><tr><td>
<asp:datagrid
id="DataGrid1"
bgcolor="#efefef"
HeaderStyle-BackColor="#718BD6"
HeaderStyle-ForeColor="#FFFF66"
AlternatingItemStyle-BackColor="#FFFFFF"
itemstyle-backcolor="#FFFFFF"
runat="server">
<ItemStyle HorizontalAlign="center" Height="20"></ItemStyle>
<Columns>

</Columns>
</asp:datagrid>
</td></tr></table>
<P>
<asp:button id="Btn_Import_Excel" runat="server" Text="轉到EXCEL"></asp:button></P>
</form>
</body>
</HTML>
------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient ;
using System.Text;
using System.Configuration;

namespace DataGrid_import_WordExcel
{

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button BtnImportWord;
protected System.Web.UI.WebControls.Button Btn_Import_Excel;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
public DataRow dr;
private DataSet myDS =new DataSet();

private void Page_Load(object sender, System.EventArgs e)
{
//CreateDataSet();
Data_Load();
if(!IsPostBack)
{
//DataBind();
}
}

#region Web 敦极扢數?汜傖腔測鎢
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Btn_Import_Excel.Click += new System.EventHandler(this.Btn_Import_Excel_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion

private void ExportDataGrid(string FileType, string FileName) //植DataGrid絳堤
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

Response.AppendHeader("Content-Disposition", "attachment;filename=" +HttpUtility.UrlEncode(FileName,Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState =false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw =new HtmlTextWriter(tw);
DataGrid1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
private void Btn_Import_Excel_Click(object sender, System.EventArgs e)
{
ExportDataGrid("application/ms-excel", "Excel.xls"); //絳善Excel
}

private void Data_Load()
{

SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["produce1"]);
SqlCommand cmd=new SqlCommand("excel",myConnection);
cmd.CommandType=CommandType.StoredProcedure;

if(Session["companyno"]!="")
{
cmd.Parameters.Add("@sql1",SqlDbType.NVarChar,50);
cmd.Parameters["@sql1"].Value = Session["companyno"];
}
else
{
cmd.Parameters.Add("@sql1",SqlDbType.NVarChar,50);
cmd.Parameters["@sql1"].Value = "";
}

myConnection.Open();

DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=cmd;
da.Fill(ds);
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
}

DataView CreateDataSource()
{
string nowDSN=ConfigurationSettings.AppSettings["produce1"];
SqlConnection myConnection=new SqlConnection(nowDSN);

SqlCommand cmd=new SqlCommand("excel",myConnection);
cmd.CommandType=CommandType.StoredProcedure;

if(Session["companyno"]!="")
{
cmd.Parameters.Add("@sql1",SqlDbType.NVarChar,50);
cmd.Parameters["@sql1"].Value = Session["companyno"];
}
else
{
cmd.Parameters.Add("@sql1",SqlDbType.NVarChar,50);
cmd.Parameters["@sql1"].Value = "";
}

DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=cmd;
da.Fill(ds);
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
return ds.Tables["block2"].DefaultView;
myConnection.Close();
Page.DataBind();
}

void DataBind()
{
DataView source=CreateDataSource();
if(!IsPostBack)
{
}
DataGrid1.DataSource = source;
DataGrid1.DataBind();
}

}
}

aliketen 2006-12-15
  • 打赏
  • 举报
回复
http://www.cnblogs.com/aliketen/articles/381486.html
ChengKing 2006-12-15
  • 打赏
  • 举报
回复
Asp.net 2.0 GridView数据导出Excel文件(示例代码下载):
http://blog.csdn.net/ChengKing/archive/2006/08/27/1128385.aspx

Asp.net 2.0 装载XML文件中数据到Excel文件中(示例代码下载):
http://blog.csdn.net/ChengKing/archive/2006/08/10/1045853.aspx


生成/读取(反向更新数据库) Excel文件(示例代码下载):
http://blog.csdn.net/ChengKing/archive/2005/11/29/539514.aspx
superman_yc 2006-12-15
  • 打赏
  • 举报
回复
网上N多
活靶子哥哥 2006-12-15
  • 打赏
  • 举报
回复
http://www.aspxboy.com/private/showthread.asp?threadid=206
http://www.aspxboy.com/private/showthread.asp?threadid=341
http://www.aspxboy.com/private/showthread.asp?threadid=401
xuqingaisensen 2006-12-15
  • 打赏
  • 举报
回复
谢谢了
andybogard 2006-10-26
  • 打赏
  • 举报
回复
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
namespace CommonFunction
{
/// <summary>
/// excel 的摘要说明。
/// </summary>
public class excel : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnGetExcel;
protected System.Web.UI.WebControls.DataGrid dgExcel;

private void Page_Load(object sender, System.EventArgs e)
{
DataSet objDataset = new DataSet();
SqlConnection objConn = new SqlConnection();
objConn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
objConn.Open();
SqlDataAdapter objAdapter = new SqlDataAdapter("Select top 5 * from customers where country='USA'",objConn);
objAdapter.Fill(objDataset);
DataView oView = new DataView(objDataset.Tables[0]);
dgExcel.DataSource = oView;
dgExcel.DataBind();
objConn.Close();
objConn.Dispose();
objConn = null;
if(Request.QueryString["bExcel"] == "1")
{
Response.ContentType = "application/vnd.ms-excel";

Response.Charset = "";

//关闭 ViewState
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
//此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
//获取control的HTML
dgExcel.RenderControl(hw);//将DATAGRID中的内容输出到HtmlTextWriter对象中
// 把HTML写回浏览器
Response.Write(tw.ToString());
Response.End();
}

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnGetExcel.Click += new System.EventHandler(this.btnGetExcel_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnGetExcel_Click(object sender, System.EventArgs e)
{
Response.Redirect("excel.aspx?bExcel=1");
}

}
}
daishengs 2006-10-26
  • 打赏
  • 举报
回复
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.datagrid1.RenderControl(oHtmlTextWriter);//改为你自己的控件,可以是TAble,也可以是TR,TD,Page.
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
yangang0201 2006-10-26
  • 打赏
  • 举报
回复
呵呵,最近也做过datagrid 导出数据到excel中,都是看的网上的文章,一收,n多,很多的代码直接的拷贝就可以用
byyt 2006-10-26
  • 打赏
  • 举报
回复
http://hades.cnblogs.com 上有不少关于.NET操作EXCEL的文章
jimu8130 2006-10-26
  • 打赏
  • 举报
回复
http://www.cnblogs.com/lingyun_k/archive/2005/11/07/271068.html
http://www.cnblogs.com/elevenWolf/archive/2004/08/21/35324.aspx
http://www.cnblogs.com/iCeSnaker/archive/2004/04/22/7273.aspx
http://www.cnblogs.com/iCeSnaker/archive/2004/04/22/7272.aspx
这几篇文章对你有帮助
Eddie005 2006-10-26
  • 打赏
  • 举报
回复
LoveCherry
技术无极限


datagrid数据导出到excel文件给客户端下载的几种方法
http://www.cnblogs.com/lovecherry/archive/2005/03/25/125519.html
REIYA 2006-10-26
  • 打赏
  • 举报
回复
DDDDDDD
jingye721 2006-10-26
  • 打赏
  • 举报
回复
<%@ Page Language="C#" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
ICollection CreateDataSource( )
{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("id", typeof(Int32)));
dt.Columns.Add(new System.Data.DataColumn("PkID", typeof(string)));
dt.Columns.Add(new System.Data.DataColumn("Title", typeof(string)));
for (int i = 0; i < 6; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "123456789123456789123456789";
dr[2] = "<a href='http://dotnet.aspx.cc/'>欢迎光临【孟宪会之精彩世界】</a>";
dt.Rows.Add(dr);
}
System.Data.DataView dv = new System.Data.DataView(dt);
return dv;
}

protected void Page_Load( object sender, EventArgs e )
{
if (!IsPostBack)
{
GridView1.BorderWidth = Unit.Pixel(2);
GridView1.BorderColor = System.Drawing.Color.DarkOrange;
GridView1.DataSource = CreateDataSource();
GridView1.DataBind();
}
}

protected void Button1_Click( object sender, System.EventArgs e )
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();

}
public override void VerifyRenderingInServerForm( Control control )
{ }
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>将 GridView 导出到 Excel 文件中</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="序号" DataField="id" />
<asp:BoundField HeaderText="身份证号" DataField="PkID" />
<asp:BoundField HeaderText="网址" DataField="Title" ReadOnly="true" HtmlEncode="false" />
</Columns>
</asp:GridView>
<asp:Literal ID="HiddenOut" runat="server" />
<asp:Button ID="Button1" runat="server" Text="导出" OnClick="Button1_Click" />
</form>
</body>
</html>

发帖
.NET社区

6.1w+

社区成员

.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
帖子事件
创建了帖子
2006-10-26 06:22
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。