将asp:Table转换为excel格式

时间:2014-03-13 11:24:30

标签: c# html asp.net excel

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

找到此警告的解决方案

所以我使用了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。

1 个答案:

答案 0 :(得分:0)

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

在幕后,Excel期望有效的XML文件格式; html虽然松散支持,但不是原生的xlsx格式。

有些库可以在互联网上将html转换为openxml,但是这可以通过迭代数据集并使用OpenXML SDK实际添加单元格和行来解决