最好的方法来使用asp.net将选定的数据转换成excel表格

我有一个SQL语句,select一个数据表,我想导出到.xls格式的Excel,我添加这个表格到一个网格视图,然后呈现该网格视图创build一个HTML编写器,并写在Excel文件使用ASP 。净。

但我一直有这个警告,文件格式和扩展名不匹配。 问题是您正在创build的文件不是一个真正的Excel文件。 这是带有.xls扩展名的HTML。

请,我需要知道什么是最好的方式将这些选定的数据导出到xls文件没有警告。

我也试过直接从dataTable中导出,但是打开excel的时候我还是得到了警告。

// these namespaces need to be added to your code behind file using System.Configuration; using System.Data.SqlClient; using System.Data; namespace MySpot.UserPages { public partial class Journal : System.Web.UI.Page { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySpotDBConnStr"].ConnectionString); DataTable dt = new DataTable(); // regular page_load from .aspx file protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } // added a button with ID=btnDownload and double clicked it's onclick event to auto create method protected void btnDownload_Click(object sender, EventArgs e) { string queryStr = "SELECT * from table"; SqlDataAdapter sda = new SqlDataAdapter(queryStr, conn); sda.Fill(dt); ExportTableData(dt); } // this does all the work to export to excel public void ExportTableData(DataTable dtdata) { string attach = "attachment;filename=journal.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attach); Response.ContentType = "application/ms-excel"; if (dtdata != null) { foreach (DataColumn dc in dtdata.Columns) { Response.Write(dc.ColumnName + "\t"); //sep = ";"; } Response.Write(System.Environment.NewLine); foreach (DataRow dr in dtdata.Rows) { for (int i = 0; i < dtdata.Columns.Count; i++) { Response.Write(dr[i].ToString() + "\t"); } Response.Write("\n"); } Response.End(); } } } } 

http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx

目前的devise不允许您在Excel中从网站打开HTML内容,除非URL的扩展名是.HTM / .HTML / .MHT / .MHTML。 因此,返回HTML并将MIMEtypes设置为XLS之类的ASP页面试图强制HTML在Excel中而不是Web浏览器中打开(如预期的那样)将始终获得安全警报,因为内容与MIMEtypes不匹配。 如果使用HTML MIMEtypes,则Web浏览器将打开内容而不是Excel。 所以对于这种情况没有很好的解决方法,因为缺less特定于Excel的HTML / MHTML的特殊MIMEtypes。 如果您同时控制需要访问的Web服务器和客户端桌面,则可以添加自己的MIMEtypes,否则最好的select是使用不同的文件格式,或者警告用户警告并告诉用户select“是”对话框。