数据库导出excel (二)
EXCEL导出二,直接用数据库导出
前文:数据库导出excel<一>
上文所述的方法,虽然速度很快。但是有一个致命的缺点,文件无法再次导入。报错为:外部表不是预期的格式
如何解决此问题?如上文所述,把原来导出的文件用excel打开另存为就OK了
可是我们不能要求客户都这么做。
在这里提出一种解决方法,希望和大家探讨。
SQL2000不是能导出EXCEL么?而且是标准的excel文件。可以用SQL生成标准的excel文件,然后推给客户端下载啊。
有了这个想法,接着就试试,结果成功了。
步骤如下:
SQL生成excel的存储过程,来自zjcxc邹健邹老大,tks:
然后生成excel,推向客户端。
原来的代码:
后来在csdn发帖,终于解决。先把excel变成二进制读入内存,删除原excel,推向客户端。
c#端代码:
终于完成。正常。
但是发布到iis会报错:
报错已经给出解决方法,添加文件夹的权限,对于本例,把F:\mycode\ExcelOut\Excel 文件夹加上aspnet帐户的完全控制权限。
OK,全部正常。
完整代码,包括前文的response输出:
后台代码:
后台:
上文所述的方法,虽然速度很快。但是有一个致命的缺点,文件无法再次导入。报错为:外部表不是预期的格式
如何解决此问题?如上文所述,把原来导出的文件用excel打开另存为就OK了
可是我们不能要求客户都这么做。
在这里提出一种解决方法,希望和大家探讨。
SQL2000不是能导出EXCEL么?而且是标准的excel文件。可以用SQL生成标准的excel文件,然后推给客户端下载啊。
有了这个想法,接着就试试,结果成功了。
步骤如下:
SQL生成excel的存储过程,来自zjcxc邹健邹老大,tks:
Code
create proc p_exporttb
@sqlstr varchar(8000), --查询语句,如果查询语句中使用了order by ,请加上top 100 percent
@path nvarchar(1000), --文件存放目录
@fname nvarchar(250), --文件名
@sheetname varchar(250)='' --要创建的工作表名,默认为文件名
as
declare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)
--参数检测
if isnull(@fname,'')='' set @fname='temp.xls'
if isnull(@sheetname,'')='' set @sheetname=replace(@fname,'.','#')
--检查文件是否已经存在
if right(@path,1)<>'\' set @path=@path+'\'
create table #tb(a bit,b bit,c bit)
set @sql=@path+@fname
insert into #tb exec master..xp_fileexist @sql
--数据库创建语句
set @sql=@path+@fname
if exists(select 1 from #tb where a=1)
set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE'
+';CREATE_DB="'+@sql+'";DBQ='+@sql
else
set @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES'
+';DATABASE='+@sql+'"'
--连接数据库
exec @err=sp_oacreate 'adodb.connection',@obj out
if @err<>0 goto lberr
exec @err=sp_oamethod @obj,'open',null,@constr
if @err<>0 goto lberr
--创建表的SQL
declare @tbname sysname
set @tbname='##tmp_'+convert(varchar(38),newid())
set @sql='select * into ['+@tbname+'] from('+@sqlstr+') a'
exec(@sql)
select @sql='',@fdlist=''
select @fdlist=@fdlist+',['+a.name+']'
,@sql=@sql+',['+a.name+'] '
+case
when b.name like '%char'
then case when a.length>255 then 'memo'
else 'text('+cast(a.length as varchar)+')' end
when b.name like '%int' or b.name='bit' then 'int'
when b.name like '%datetime' then 'datetime'
when b.name like '%money' then 'money'
when b.name like '%text' then 'memo'
else b.name end
FROM tempdb..syscolumns a left join tempdb..systypes b on a.xtype=b.xusertype
where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp')
and a.id=(select id from tempdb..sysobjects where name=@tbname)
if @@rowcount=0 return
select @sql='create table ['+@sheetname
+']('+substring(@sql,2,8000)+')'
,@fdlist=substring(@fdlist,2,8000)
exec @err=sp_oamethod @obj,'execute',@out out,@sql
if @err<>0 goto lberr
exec @err=sp_oadestroy @obj
--导入数据
set @sql='openrowset(''MICROSOFT.JET.OLEDB.4.0'',''Excel 8.0;HDR=YES
;DATABASE='+@path+@fname+''',['+@sheetname+'$])'
exec('insert into '+@sql+'('+@fdlist+') select '+@fdlist+' from ['+@tbname+']')
set @sql='drop table ['+@tbname+']'
exec(@sql)
return
lberr:
exec sp_oageterrorinfo 0,@src out,@desc out
lbexit:
select cast(@err as varbinary(4)) as 错误号
,@src as 错误源,@desc as 错误描述
select @sql,@constr,@fdlist
GO
create proc p_exporttb
@sqlstr varchar(8000), --查询语句,如果查询语句中使用了order by ,请加上top 100 percent
@path nvarchar(1000), --文件存放目录
@fname nvarchar(250), --文件名
@sheetname varchar(250)='' --要创建的工作表名,默认为文件名
as
declare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)
--参数检测
if isnull(@fname,'')='' set @fname='temp.xls'
if isnull(@sheetname,'')='' set @sheetname=replace(@fname,'.','#')
--检查文件是否已经存在
if right(@path,1)<>'\' set @path=@path+'\'
create table #tb(a bit,b bit,c bit)
set @sql=@path+@fname
insert into #tb exec master..xp_fileexist @sql
--数据库创建语句
set @sql=@path+@fname
if exists(select 1 from #tb where a=1)
set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE'
+';CREATE_DB="'+@sql+'";DBQ='+@sql
else
set @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES'
+';DATABASE='+@sql+'"'
--连接数据库
exec @err=sp_oacreate 'adodb.connection',@obj out
if @err<>0 goto lberr
exec @err=sp_oamethod @obj,'open',null,@constr
if @err<>0 goto lberr
--创建表的SQL
declare @tbname sysname
set @tbname='##tmp_'+convert(varchar(38),newid())
set @sql='select * into ['+@tbname+'] from('+@sqlstr+') a'
exec(@sql)
select @sql='',@fdlist=''
select @fdlist=@fdlist+',['+a.name+']'
,@sql=@sql+',['+a.name+'] '
+case
when b.name like '%char'
then case when a.length>255 then 'memo'
else 'text('+cast(a.length as varchar)+')' end
when b.name like '%int' or b.name='bit' then 'int'
when b.name like '%datetime' then 'datetime'
when b.name like '%money' then 'money'
when b.name like '%text' then 'memo'
else b.name end
FROM tempdb..syscolumns a left join tempdb..systypes b on a.xtype=b.xusertype
where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp')
and a.id=(select id from tempdb..sysobjects where name=@tbname)
if @@rowcount=0 return
select @sql='create table ['+@sheetname
+']('+substring(@sql,2,8000)+')'
,@fdlist=substring(@fdlist,2,8000)
exec @err=sp_oamethod @obj,'execute',@out out,@sql
if @err<>0 goto lberr
exec @err=sp_oadestroy @obj
--导入数据
set @sql='openrowset(''MICROSOFT.JET.OLEDB.4.0'',''Excel 8.0;HDR=YES
;DATABASE='+@path+@fname+''',['+@sheetname+'$])'
exec('insert into '+@sql+'('+@fdlist+') select '+@fdlist+' from ['+@tbname+']')
set @sql='drop table ['+@tbname+']'
exec(@sql)
return
lberr:
exec sp_oageterrorinfo 0,@src out,@desc out
lbexit:
select cast(@err as varbinary(4)) as 错误号
,@src as 错误源,@desc as 错误描述
select @sql,@constr,@fdlist
GO
然后生成excel,推向客户端。
原来的代码:
Code
string name = "123.xls";
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";
Response.WriteFile(name);
Response.End();
System.IO.File.Delete(Server.MapPath(name));
问题出在推客户端这里,response流执行时,无法删除文件。难道咱们就永远让这这些文件存在服务器上?OMG。string name = "123.xls";
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";
Response.WriteFile(name);
Response.End();
System.IO.File.Delete(Server.MapPath(name));
后来在csdn发帖,终于解决。先把excel变成二进制读入内存,删除原excel,推向客户端。
c#端代码:
Code
protected void Button2_Click(object sender, EventArgs e)
{
string path = @"F:\mycode\ExcelOut\Excel\";//生成excel的临时文件夹
string filename = "测试_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";//生成excel的名字
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;database=NorthWind;uid=sa;pwd=;";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "p_exporttb";
SqlParameter[] param = new SqlParameter[] { new SqlParameter("@sqlstr",SqlDbType.VarChar,8000),
new SqlParameter("@path",SqlDbType.VarChar,1000),
new SqlParameter("@fname",SqlDbType.VarChar,250),
new SqlParameter("@sheetname",SqlDbType.VarChar,250)
};
param[0].Value = "SELECT TOP 20 CompanyName as 公司名称,ContactName as 联系人,Address as 地址,City as 城市,PostalCode as 邮编,Country as 国家,Phone as 电话,fax as 传真 FROM Customers ORDER BY CustomerID";
param[1].Value = path;
param[2].Value = filename;
param[3].Value = "Infomation";
foreach (SqlParameter sql in param)
{
cmd.Parameters.Add(sql);
}
cmd.ExecuteNonQuery();
conn.Close();
//把文件先变成二进制流,删除文件,然后把此excel推向客户端下载
string fileAllPath = path + filename;
FileStream fsManuscript = new FileStream(fileAllPath, FileMode.Open, FileAccess.Read, FileShare.Read);
int rgfilesize = Convert.ToInt32(fsManuscript.Length);
byte[] byteArrManuscriptContent = new byte[rgfilesize];
fsManuscript.Read(byteArrManuscriptContent, 0, rgfilesize);
fsManuscript.Close();
fsManuscript.Dispose();
//删除文件
if (File.Exists(fileAllPath))
{
File.Delete(fileAllPath);
}
// 下载文件
string downloadFileName = filename;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(downloadFileName, System.Text.Encoding.UTF8) + ";");
Response.BinaryWrite(byteArrManuscriptContent);
Response.End();
}
protected void Button2_Click(object sender, EventArgs e)
{
string path = @"F:\mycode\ExcelOut\Excel\";//生成excel的临时文件夹
string filename = "测试_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";//生成excel的名字
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;database=NorthWind;uid=sa;pwd=;";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "p_exporttb";
SqlParameter[] param = new SqlParameter[] { new SqlParameter("@sqlstr",SqlDbType.VarChar,8000),
new SqlParameter("@path",SqlDbType.VarChar,1000),
new SqlParameter("@fname",SqlDbType.VarChar,250),
new SqlParameter("@sheetname",SqlDbType.VarChar,250)
};
param[0].Value = "SELECT TOP 20 CompanyName as 公司名称,ContactName as 联系人,Address as 地址,City as 城市,PostalCode as 邮编,Country as 国家,Phone as 电话,fax as 传真 FROM Customers ORDER BY CustomerID";
param[1].Value = path;
param[2].Value = filename;
param[3].Value = "Infomation";
foreach (SqlParameter sql in param)
{
cmd.Parameters.Add(sql);
}
cmd.ExecuteNonQuery();
conn.Close();
//把文件先变成二进制流,删除文件,然后把此excel推向客户端下载
string fileAllPath = path + filename;
FileStream fsManuscript = new FileStream(fileAllPath, FileMode.Open, FileAccess.Read, FileShare.Read);
int rgfilesize = Convert.ToInt32(fsManuscript.Length);
byte[] byteArrManuscriptContent = new byte[rgfilesize];
fsManuscript.Read(byteArrManuscriptContent, 0, rgfilesize);
fsManuscript.Close();
fsManuscript.Dispose();
//删除文件
if (File.Exists(fileAllPath))
{
File.Delete(fileAllPath);
}
// 下载文件
string downloadFileName = filename;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(downloadFileName, System.Text.Encoding.UTF8) + ";");
Response.BinaryWrite(byteArrManuscriptContent);
Response.End();
}
终于完成。正常。
但是发布到iis会报错:
报错已经给出解决方法,添加文件夹的权限,对于本例,把F:\mycode\ExcelOut\Excel 文件夹加上aspnet帐户的完全控制权限。
OK,全部正常。
完整代码,包括前文的response输出:
后台代码:
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Excel导出测试</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Response导出" OnClick="Button1_Click" />
<br />
<br />
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="数据库直接导出" /></div>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Excel导出测试</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Response导出" OnClick="Button1_Click" />
<br />
<br />
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="数据库直接导出" /></div>
</form>
</body>
</html>
后台:
Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region
/// <summary>
/// 导出excel 转自http://blog.csdn.net/tippointGmail/archive/2008/06/27/2591219.aspx
/// 自己稍作修改
/// </summary>
/// <param name="ds">DataSet,数据源</param>
/// <param name="sheetName">工作表名</param>
/// <param name="fileName">输出的文件名</param>
/// <param name="columnName">列名称</param>
/// <param name="columnData">列数据</param>
public void CreateExcel(DataSet ds, string sheetName, string fileName, string[] columnName, string[] columnData)
{
StringBuilder strb = new StringBuilder();
strb.Append(" <html xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
strb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
strb.Append("xmlns=\"http://www.w3.org/TR/REC-html40\"");
strb.Append(" <head> <meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
strb.Append(" <style>");
strb.Append(".xl26");
strb.Append(" {mso-style-parent:style0;");
strb.Append(" font-family:\"Times New Roman\", serif;");
strb.Append(" mso-font-charset:0;");
strb.Append(" mso-number-format:\"@\";}");
strb.Append(" </style>");
strb.Append(" <xml>");
strb.Append(" <x:ExcelWorkbook>");
strb.Append(" <x:ExcelWorksheets>");
strb.Append(" <x:ExcelWorksheet>");
//设置工作组名
strb.Append(" <x:Name>" + sheetName.ToString().Trim() + "</x:Name>");
strb.Append(" <x:WorksheetOptions>");
strb.Append(" <x:DefaultRowHeight>285 </x:DefaultRowHeight>");
strb.Append(" <x:Selected/>");
strb.Append(" <x:Panes>");
strb.Append(" <x:Pane>");
strb.Append(" <x:Number>3 </x:Number>");
strb.Append(" <x:ActiveCol>1 </x:ActiveCol>");
strb.Append(" </x:Pane>");
strb.Append(" </x:Panes>");
strb.Append(" <x:ProtectContents>False </x:ProtectContents>");
strb.Append(" <x:ProtectObjects>False </x:ProtectObjects>");
strb.Append(" <x:ProtectScenarios>False </x:ProtectScenarios>");
strb.Append(" </x:WorksheetOptions>");
strb.Append(" </x:ExcelWorksheet>");
strb.Append(" <x:WindowHeight>6750 </x:WindowHeight>");
strb.Append(" <x:WindowWidth>10620 </x:WindowWidth>");
strb.Append(" <x:WindowTopX>480 </x:WindowTopX>");
strb.Append(" <x:WindowTopY>75 </x:WindowTopY>");
strb.Append(" <x:ProtectStructure>False </x:ProtectStructure>");
strb.Append(" <x:ProtectWindows>False </x:ProtectWindows>");
strb.Append(" </x:ExcelWorkbook>");
strb.Append(" </xml>");
strb.Append("");
strb.Append(" </head> <body> <table align=\"center\" style='border-collapse:collapse;table-layout:fixed';> <tr>");
string tempInfo = string.Empty;
if (ds.Tables.Count > 0)
{
//写列标题
int columncount = ds.Tables[0].Columns.Count;
foreach (string title in columnName)
{
strb.Append(" <td> <b>" + title + " </b> </td>");
}
strb.Append(" </tr>");
//写数据
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
strb.Append(" <tr>");
foreach (string str in columnData)
{
tempInfo = ds.Tables[0].Rows[i][str].ToString().Trim();
strb.Append(" <td class='xl26'>" + tempInfo + " </td>");
}
strb.Append(" </tr>");
}
}
strb.Append(" </body> </html>");
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
Response.Write(strb);
Response.Flush();
Response.End();
}
#endregion
#region
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;database=NorthWind;uid=sa;pwd=;";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT TOP 20 * FROM Customers ORDER BY 1";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
string[] columnName = new string[] {"公司名称","联系人","地址","城市","邮编","国家","电话","传真"};
string[] columnData = new string[] { "CompanyName", "ContactName", "Address", "City", "PostalCode", "Country", "Phone", "Fax" };
this.CreateExcel(ds, "Infomation", HttpUtility.UrlEncode("测试导出EXCEL_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", System.Text.Encoding.UTF8), columnName, columnData);
}
#endregion
protected void Button2_Click(object sender, EventArgs e)
{
string path = @"F:\mycode\ExcelOut\Excel\";//生成excel的临时文件夹
string filename = "测试_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";//生成excel的名字
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;database=NorthWind;uid=sa;pwd=;";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "p_exporttb";
SqlParameter[] param = new SqlParameter[] { new SqlParameter("@sqlstr",SqlDbType.VarChar,8000),
new SqlParameter("@path",SqlDbType.VarChar,1000),
new SqlParameter("@fname",SqlDbType.VarChar,250),
new SqlParameter("@sheetname",SqlDbType.VarChar,250)
};
param[0].Value = "SELECT TOP 20 CompanyName as 公司名称,ContactName as 联系人,Address as 地址,City as 城市,PostalCode as 邮编,Country as 国家,Phone as 电话,fax as 传真 FROM Customers ORDER BY CustomerID";
param[1].Value = path;
param[2].Value = filename;
param[3].Value = "Infomation";
foreach (SqlParameter sql in param)
{
cmd.Parameters.Add(sql);
}
cmd.ExecuteNonQuery();
conn.Close();
//把文件先变成二进制流,删除文件,然后把此excel推向客户端下载
string fileAllPath = path + filename;
FileStream fsManuscript = new FileStream(fileAllPath, FileMode.Open, FileAccess.Read, FileShare.Read);
int rgfilesize = Convert.ToInt32(fsManuscript.Length);
byte[] byteArrManuscriptContent = new byte[rgfilesize];
fsManuscript.Read(byteArrManuscriptContent, 0, rgfilesize);
fsManuscript.Close();
fsManuscript.Dispose();
//删除文件
if (File.Exists(fileAllPath))
{
File.Delete(fileAllPath);
}
// 下载文件
string downloadFileName = filename;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(downloadFileName, System.Text.Encoding.UTF8) + ";");
Response.BinaryWrite(byteArrManuscriptContent);
Response.End();
}
}
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region
/// <summary>
/// 导出excel 转自http://blog.csdn.net/tippointGmail/archive/2008/06/27/2591219.aspx
/// 自己稍作修改
/// </summary>
/// <param name="ds">DataSet,数据源</param>
/// <param name="sheetName">工作表名</param>
/// <param name="fileName">输出的文件名</param>
/// <param name="columnName">列名称</param>
/// <param name="columnData">列数据</param>
public void CreateExcel(DataSet ds, string sheetName, string fileName, string[] columnName, string[] columnData)
{
StringBuilder strb = new StringBuilder();
strb.Append(" <html xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
strb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
strb.Append("xmlns=\"http://www.w3.org/TR/REC-html40\"");
strb.Append(" <head> <meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
strb.Append(" <style>");
strb.Append(".xl26");
strb.Append(" {mso-style-parent:style0;");
strb.Append(" font-family:\"Times New Roman\", serif;");
strb.Append(" mso-font-charset:0;");
strb.Append(" mso-number-format:\"@\";}");
strb.Append(" </style>");
strb.Append(" <xml>");
strb.Append(" <x:ExcelWorkbook>");
strb.Append(" <x:ExcelWorksheets>");
strb.Append(" <x:ExcelWorksheet>");
//设置工作组名
strb.Append(" <x:Name>" + sheetName.ToString().Trim() + "</x:Name>");
strb.Append(" <x:WorksheetOptions>");
strb.Append(" <x:DefaultRowHeight>285 </x:DefaultRowHeight>");
strb.Append(" <x:Selected/>");
strb.Append(" <x:Panes>");
strb.Append(" <x:Pane>");
strb.Append(" <x:Number>3 </x:Number>");
strb.Append(" <x:ActiveCol>1 </x:ActiveCol>");
strb.Append(" </x:Pane>");
strb.Append(" </x:Panes>");
strb.Append(" <x:ProtectContents>False </x:ProtectContents>");
strb.Append(" <x:ProtectObjects>False </x:ProtectObjects>");
strb.Append(" <x:ProtectScenarios>False </x:ProtectScenarios>");
strb.Append(" </x:WorksheetOptions>");
strb.Append(" </x:ExcelWorksheet>");
strb.Append(" <x:WindowHeight>6750 </x:WindowHeight>");
strb.Append(" <x:WindowWidth>10620 </x:WindowWidth>");
strb.Append(" <x:WindowTopX>480 </x:WindowTopX>");
strb.Append(" <x:WindowTopY>75 </x:WindowTopY>");
strb.Append(" <x:ProtectStructure>False </x:ProtectStructure>");
strb.Append(" <x:ProtectWindows>False </x:ProtectWindows>");
strb.Append(" </x:ExcelWorkbook>");
strb.Append(" </xml>");
strb.Append("");
strb.Append(" </head> <body> <table align=\"center\" style='border-collapse:collapse;table-layout:fixed';> <tr>");
string tempInfo = string.Empty;
if (ds.Tables.Count > 0)
{
//写列标题
int columncount = ds.Tables[0].Columns.Count;
foreach (string title in columnName)
{
strb.Append(" <td> <b>" + title + " </b> </td>");
}
strb.Append(" </tr>");
//写数据
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
strb.Append(" <tr>");
foreach (string str in columnData)
{
tempInfo = ds.Tables[0].Rows[i][str].ToString().Trim();
strb.Append(" <td class='xl26'>" + tempInfo + " </td>");
}
strb.Append(" </tr>");
}
}
strb.Append(" </body> </html>");
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
Response.Write(strb);
Response.Flush();
Response.End();
}
#endregion
#region
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;database=NorthWind;uid=sa;pwd=;";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT TOP 20 * FROM Customers ORDER BY 1";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
string[] columnName = new string[] {"公司名称","联系人","地址","城市","邮编","国家","电话","传真"};
string[] columnData = new string[] { "CompanyName", "ContactName", "Address", "City", "PostalCode", "Country", "Phone", "Fax" };
this.CreateExcel(ds, "Infomation", HttpUtility.UrlEncode("测试导出EXCEL_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", System.Text.Encoding.UTF8), columnName, columnData);
}
#endregion
protected void Button2_Click(object sender, EventArgs e)
{
string path = @"F:\mycode\ExcelOut\Excel\";//生成excel的临时文件夹
string filename = "测试_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";//生成excel的名字
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=.;database=NorthWind;uid=sa;pwd=;";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "p_exporttb";
SqlParameter[] param = new SqlParameter[] { new SqlParameter("@sqlstr",SqlDbType.VarChar,8000),
new SqlParameter("@path",SqlDbType.VarChar,1000),
new SqlParameter("@fname",SqlDbType.VarChar,250),
new SqlParameter("@sheetname",SqlDbType.VarChar,250)
};
param[0].Value = "SELECT TOP 20 CompanyName as 公司名称,ContactName as 联系人,Address as 地址,City as 城市,PostalCode as 邮编,Country as 国家,Phone as 电话,fax as 传真 FROM Customers ORDER BY CustomerID";
param[1].Value = path;
param[2].Value = filename;
param[3].Value = "Infomation";
foreach (SqlParameter sql in param)
{
cmd.Parameters.Add(sql);
}
cmd.ExecuteNonQuery();
conn.Close();
//把文件先变成二进制流,删除文件,然后把此excel推向客户端下载
string fileAllPath = path + filename;
FileStream fsManuscript = new FileStream(fileAllPath, FileMode.Open, FileAccess.Read, FileShare.Read);
int rgfilesize = Convert.ToInt32(fsManuscript.Length);
byte[] byteArrManuscriptContent = new byte[rgfilesize];
fsManuscript.Read(byteArrManuscriptContent, 0, rgfilesize);
fsManuscript.Close();
fsManuscript.Dispose();
//删除文件
if (File.Exists(fileAllPath))
{
File.Delete(fileAllPath);
}
// 下载文件
string downloadFileName = filename;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(downloadFileName, System.Text.Encoding.UTF8) + ";");
Response.BinaryWrite(byteArrManuscriptContent);
Response.End();
}
}