我建議使用Excel文件擴展名創建實際的Excel文件,而不是CSV或HTML。
完成此操作的一個簡單方法是使用ClosedXML。
爲此,請從codeplex站點下載ClosedXML.dll和DocumentFormat.OpenXml.dll,並將它們作爲參考添加到ASP.NET項目中。然後,在按鈕單擊事件中,您可以簡單地設置Excel工作簿,根據您綁定到GridView
的相同DataTable
創建工作表,並將工作簿文件保存在HTTP響應中。事情是這樣的:
var wb = new ClosedXML.Excel.XLWorkbook();
DataTable dt = GetTheDataTable();
dt.TableName = "This will be the worksheet name";
wb.Worksheets.Add(dt);
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");
using (var ms = new System.IO.MemoryStream()) {
wb.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
ms.Close();
}
Response.End();
我會用ClosedXML去了其他的替代品,因爲許可限制較少,該文件是一流的,開發商是有幫助的,友好的,並且該項目目前非常活躍。
你試試..?把你的代碼,你有嘗試 – 2012-08-08 10:29:40
請顯示您的代碼。 – SMK 2012-08-08 10:30:03
完全重複http://stackoverflow.com/questions/9799726/why-showing-error-message-while-opening-xls-file – SMK 2012-08-08 10:31:18