我能夠從asp:table生成excel文件,但是在生成excel文件的同時打開文件時會發出警告。 文件,你試圖打開是在不同的格式由文件擴展名我已經找到解決這一警告來自這個鏈接http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-file-extension.aspx將asp:Table轉換爲excel格式
,所以我已經使用ClosedXML圖書館規定,但同時將數據添加到Excel工作表中它接受確定時代,僅數據集格式,我得到了字符串格式的數據,因此它生成空白的Excel表格。請檢查我嘗試過的代碼。
LoadDetailsToTable();
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
tbl_loctbl.RenderControl(hw);
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("asd");
ws.Cell(2, 1).InsertTable(sw.ToString());
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename=newfile.xlsx"));
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
MyMemoryStream.Close();
}
HttpContext.Current.Response.End();
}
這裏LoadDetailsToTable()函數加載數據到ASP表。 tbl_loctbl是表格ID。