将数据表导出到Excel而不考虑HTML标记

时间:2013-12-24 09:19:44

标签: c# c#-4.0 export-to-excel

有很多方法可以将数据表导出到Excel文件。

但是当列包含HTML标记时,Excel的结构已损坏,它看起来像HTML文档。

如何在不考虑HTML标记的情况下阻止将数据表导出为Excel?

我使用的代码如下:

public static void ExportToExcel(DataTable table, string name)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Clear();
        foreach (DataColumn column in table.Columns)
        {
            context.Response.Write(column.ColumnName + ",");
        }
        context.Response.Write(Environment.NewLine);
        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
            }
            context.Response.Write(Environment.NewLine);
        }
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".xls");
        context.Response.End();
    }

1 个答案:

答案 0 :(得分:0)

使用epplus

private void CreateExcel(DataTable dataTable)
        {
            using (ExcelPackage pck = new ExcelPackage())
            {
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

                ws.Cells["A1"].LoadFromDataTable(dataTable, true);                

                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
                Response.BinaryWrite(pck.GetAsByteArray());
            }
        }