怎么在服务器生成excle文件,并在客户端打开或下载? 如题 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 楼主说的应该是导出数据时生成EXCEL吧? 下面代码实现将 GridView 导出到 Excel文件中。值得注意的是VerifyRenderingInServerForm重载方法: MSDN上的 VerifyRenderingInServerForm 方法的描述: 必须位于 <form runat=server> 标记中的控件可以在呈现之前调用此方法,以便在控件被置于标记外时显示错误信息。发送回或依赖于注册的脚本块的控件应该在 Control.Render 方法的重写中调用此方法。呈现服务器窗体元素的方式不同的页可以重写此方法以在不同的条件下引发异常。 如果回发或使用客户端脚本的服务器控件没有包含在 HtmlForm 服务器控件 (<form runat="server">) 标记中,它们将无法正常工作。这些控件可以在呈现时调用该方法,以在它们没有包含在 HtmlForm 控件中时提供明确的错误信息。 开发自定义服务器控件时,通常在为任何类型的输入标记重写 Render 方法时调用该方法。这在输入控件调用 GetPostBackEventReference 或发出客户端脚本时尤其重要。复合服务器控件不需要作出此调用。 没有这个方法,程序将报错。C# 代码<%...@ 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> 网上一搜一堆啊,下面这个就是我在网上搜的但数据量一旦超过1W条,速度不容乐观啊 /// <summary> /// 将传入的DataSet数据导出至Excel文件 /// </summary> /// <param name="ctl">DataGrid</param> public void DataSet2Excel(DataTable _dtbData) { int maxRow = _dtbData.Rows.Count; string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称 DataView dv = new DataView(_dtbData);//将DataSet转换成DataView string fileURL = string.Empty; //调用方法将文件写入服务器,并获取全部路径 fileURL = DataView2ExcelBySheet(dv, fileName); //获取路径后从服务器下载文件至本地 HttpContext curContext = System.Web.HttpContext.Current; curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.Default; curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName)); curContext.Response.Charset = ""; curContext.Response.WriteFile(fileURL); curContext.Response.Flush(); curContext.Response.End(); //curContext.ApplicationInstance.CompleteRequest(); if (File.Exists(fileURL)) { File.Delete(fileURL); } } /// <summary> /// 分Sheet导出Excel文件 /// </summary> /// <param name="dv">需导出的DataView</param> /// <returns>导出文件的路径</returns> private static string DataView2ExcelBySheet(DataView dv, string fileName) { int sheetRows = 65535;//设置Sheet的行数,此为最大上限,本来是65536,因表头要占去一行 int sheetCount = (dv.Table.Rows.Count - 1) / sheetRows + 1;//计算Sheet数 GC.Collect();//垃圾回收 Microsoft.Office.Interop.Excel.Application excel = null; Microsoft.Office.Interop.Excel._Workbook xBk = null; Microsoft.Office.Interop.Excel._Worksheet xSt = null; excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); xBk = excel.Workbooks.Add(true); //定义循环中要使用的变量 int dvRowStart; int dvRowEnd; int rowIndex = 0; int colIndex = 0; //对全部Sheet进行操作 for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) { //初始化Sheet中的变量 rowIndex = 1; colIndex = 1; //计算起始行 dvRowStart = sheetIndex * sheetRows; dvRowEnd = dvRowStart + sheetRows - 1; if (dvRowEnd > dv.Table.Rows.Count - 1) { dvRowEnd = dv.Table.Rows.Count - 1; } //创建一个Sheet if (null == xSt) { xSt = (Microsoft.Office.Interop.Excel._Worksheet)xBk.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing); } else { xSt = (Microsoft.Office.Interop.Excel._Worksheet)xBk.Worksheets.Add(Type.Missing, xSt, 1, Type.Missing); } //设置Sheet的名称 xSt.Name = "Expdata"; if (sheetCount > 1) { xSt.Name += ((int)(sheetIndex + 1)).ToString(); } //取得标题 foreach (DataColumn col in dv.Table.Columns) { //设置标题格式 xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; //设置标题居中对齐 xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).Font.Bold = true;//设置标题为粗体 //填值,并进行下一列 excel.Cells[rowIndex, colIndex++] = col.ColumnName; } //取得表格中数量 int drvIndex; for (drvIndex = dvRowStart; drvIndex <= dvRowEnd; drvIndex++) { DataRowView row = dv[drvIndex]; //新起一行,当前单元格移至行首 rowIndex++; colIndex = 1; foreach (DataColumn col in dv.Table.Columns) { //if (col.DataType == System.Type.GetType("System.String")) //{ excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString(); //} //else //{ // excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString(); //} colIndex++; } } //使用最佳宽度 Microsoft.Office.Interop.Excel.Range allDataWithTitleRange = xSt.get_Range(excel.Cells[1, 1], excel.Cells[rowIndex, colIndex - 1]); allDataWithTitleRange.Select(); allDataWithTitleRange.Columns.AutoFit(); allDataWithTitleRange.Borders.LineStyle = 1;//将导出Excel加上边框 } //设置导出文件在服务器上的文件夹 string exportDir = "~/ExcelFile/";//注意:该文件夹您须事先在服务器上建好才行 //设置文件在服务器上的路径 string absFileName = HttpContext.Current.Server.MapPath(System.IO.Path.Combine(exportDir, fileName)); xBk.SaveCopyAs(absFileName); xBk.Close(false, null, null); excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk); System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt); xBk = null; excel = null; xSt = null; GC.Collect(); //返回写入服务器Excel文件的路径 return absFileName; } 求:一个用CSS+DIV布局的asp.net网站的实例 求教.NET 2.0前台下的一个问提 远程MSMQ Menu放入Session后取出的问题 问2个100问题 各100分 模块function返回一个string array,在用VB写得ASP中调用,不知如何 MsChar 在VS2008中柱状图的问题 请教关于使用手机发送短信 关于JS数组动态赋值问题 datediff 怎么使dropdownlist下拉列表内容(数字)同时扩大100倍? 我想要一个简单的Extjs 编辑grid,添加新行,删除一或多行
MSDN上的 VerifyRenderingInServerForm 方法的描述:
必须位于 <form runat=server> 标记中的控件可以在呈现之前调用此方法,以便在控件被置于标记外时显示错误信息。发送回或依赖于注册的脚本块的控件应该在 Control.Render 方法的重写中调用此方法。呈现服务器窗体元素的方式不同的页可以重写此方法以在不同的条件下引发异常。
如果回发或使用客户端脚本的服务器控件没有包含在 HtmlForm 服务器控件 (<form runat="server">) 标记中,它们将无法正常工作。这些控件可以在呈现时调用该方法,以在它们没有包含在 HtmlForm 控件中时提供明确的错误信息。
开发自定义服务器控件时,通常在为任何类型的输入标记重写 Render 方法时调用该方法。这在输入控件调用 GetPostBackEventReference 或发出客户端脚本时尤其重要。复合服务器控件不需要作出此调用。 没有这个方法,程序将报错。C# 代码<%...@ 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>
但数据量一旦超过1W条,速度不容乐观啊 /// <summary>
/// 将传入的DataSet数据导出至Excel文件
/// </summary>
/// <param name="ctl">DataGrid</param>
public void DataSet2Excel(DataTable _dtbData)
{
int maxRow = _dtbData.Rows.Count;
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称 DataView dv = new DataView(_dtbData);//将DataSet转换成DataView
string fileURL = string.Empty;
//调用方法将文件写入服务器,并获取全部路径
fileURL = DataView2ExcelBySheet(dv, fileName);
//获取路径后从服务器下载文件至本地
HttpContext curContext = System.Web.HttpContext.Current;
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.Default;
curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
curContext.Response.Charset = ""; curContext.Response.WriteFile(fileURL);
curContext.Response.Flush();
curContext.Response.End();
//curContext.ApplicationInstance.CompleteRequest(); if (File.Exists(fileURL))
{
File.Delete(fileURL);
}
} /// <summary>
/// 分Sheet导出Excel文件
/// </summary>
/// <param name="dv">需导出的DataView</param>
/// <returns>导出文件的路径</returns>
private static string DataView2ExcelBySheet(DataView dv, string fileName)
{
int sheetRows = 65535;//设置Sheet的行数,此为最大上限,本来是65536,因表头要占去一行
int sheetCount = (dv.Table.Rows.Count - 1) / sheetRows + 1;//计算Sheet数 GC.Collect();//垃圾回收 Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel._Workbook xBk = null;
Microsoft.Office.Interop.Excel._Worksheet xSt = null;
excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
xBk = excel.Workbooks.Add(true); //定义循环中要使用的变量
int dvRowStart;
int dvRowEnd;
int rowIndex = 0;
int colIndex = 0;
//对全部Sheet进行操作
for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++)
{
//初始化Sheet中的变量
rowIndex = 1;
colIndex = 1;
//计算起始行
dvRowStart = sheetIndex * sheetRows;
dvRowEnd = dvRowStart + sheetRows - 1;
if (dvRowEnd > dv.Table.Rows.Count - 1)
{
dvRowEnd = dv.Table.Rows.Count - 1;
}
//创建一个Sheet
if (null == xSt)
{
xSt = (Microsoft.Office.Interop.Excel._Worksheet)xBk.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
}
else
{
xSt = (Microsoft.Office.Interop.Excel._Worksheet)xBk.Worksheets.Add(Type.Missing, xSt, 1, Type.Missing);
}
//设置Sheet的名称
xSt.Name = "Expdata";
if (sheetCount > 1)
{
xSt.Name += ((int)(sheetIndex + 1)).ToString();
}
//取得标题
foreach (DataColumn col in dv.Table.Columns)
{
//设置标题格式
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; //设置标题居中对齐
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).Font.Bold = true;//设置标题为粗体
//填值,并进行下一列
excel.Cells[rowIndex, colIndex++] = col.ColumnName;
}
//取得表格中数量
int drvIndex;
for (drvIndex = dvRowStart; drvIndex <= dvRowEnd; drvIndex++)
{
DataRowView row = dv[drvIndex];
//新起一行,当前单元格移至行首
rowIndex++;
colIndex = 1;
foreach (DataColumn col in dv.Table.Columns)
{ //if (col.DataType == System.Type.GetType("System.String"))
//{
excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
//}
//else
//{
// excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
//}
colIndex++;
}
}
//使用最佳宽度
Microsoft.Office.Interop.Excel.Range allDataWithTitleRange = xSt.get_Range(excel.Cells[1, 1], excel.Cells[rowIndex, colIndex - 1]);
allDataWithTitleRange.Select();
allDataWithTitleRange.Columns.AutoFit();
allDataWithTitleRange.Borders.LineStyle = 1;//将导出Excel加上边框
}
//设置导出文件在服务器上的文件夹
string exportDir = "~/ExcelFile/";//注意:该文件夹您须事先在服务器上建好才行
//设置文件在服务器上的路径
string absFileName = HttpContext.Current.Server.MapPath(System.IO.Path.Combine(exportDir, fileName));
xBk.SaveCopyAs(absFileName);
xBk.Close(false, null, null);
excel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt); xBk = null;
excel = null;
xSt = null;
GC.Collect();
//返回写入服务器Excel文件的路径
return absFileName;
}