数据库导出excel的方法主要为两种:采用流方式,模拟html,另外是采用excel api。前者的速度快,但是导出为"伪excel",用记事本打开可以看到table的标记。后者的速度慢,导出为正在的excel文件,而且功能强大,但是这种方式服务器端要安装office,有些囧。
公司之前采用response流的方式输出为excel。但是周围有白边。后从网上找到了一个代码,设置了字体。自己稍作修改。
看代码,可以自定义列名。当然数据需要一一对应。
或者直接在数据库里面自定义列名也可以,不过不太通用。
Code
/// <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();
}
/// <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();
}
运行结果:
导出的代码,很简单(用SQL2000自带的NorthWind做测试)
Code
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);
}
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);
}
运行结果:
但是用记事本打开此文件一看:
Code
<table align="center" style='border-collapse:collapse;table-layout:fixed';> <tr> <td> <b>公司名称 </b> </td> <td> <b>联系人 </b> </td> <td> <b>地址 </b> </td> <td> <b>城市 </b> </td> <td> <b>邮编 </b> </td> <td> <b>国家 </b> </td> <td> <b>电话 </b> </td> <td> <b>传真 </b> </td> </tr> <tr> <td class='xl26'>Alfreds Futterkiste </td> <td class='xl26'>Maria Anders </td> <td class='xl26'>Obere Str. 57 </td> <td class='xl26'>Berlin </td> <td class='xl26'>12209 </td> <td class='xl26'>Germany </td>
.
如果用此excel导入数据库,会报错:"外部表不是预期的格式".<table align="center" style='border-collapse:collapse;table-layout:fixed';> <tr> <td> <b>公司名称 </b> </td> <td> <b>联系人 </b> </td> <td> <b>地址 </b> </td> <td> <b>城市 </b> </td> <td> <b>邮编 </b> </td> <td> <b>国家 </b> </td> <td> <b>电话 </b> </td> <td> <b>传真 </b> </td> </tr> <tr> <td class='xl26'>Alfreds Futterkiste </td> <td class='xl26'>Maria Anders </td> <td class='xl26'>Obere Str. 57 </td> <td class='xl26'>Berlin </td> <td class='xl26'>12209 </td> <td class='xl26'>Germany </td>
.
可见不是真正的excel。当然也有简单的方法,把之前导出的excel用office excel打开,另存为.xls文件,就是真正的excel文件。
下一篇,自己提出解决此问题的方法。
地址:数据库导出excel<二>