2014-03-13 43 views
2

我能够从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。

回答

0

不幸的是,您使用的两个标记是不兼​​容的。 Excel中的HTML表格标记是受支持的,但它不在OpenXML中,这是您的库期望输出的内容。

在引擎盖下,Excel期待有效的XML文件格式; html虽然松散地支持,但不是原生的xlsx格式。

有将将HTML转换成OpenXML的在互联网上可用的库,但是这可以通过遍历数据集和实际使用OpenXML SDK

添加单元格和行解决