将数据表转换为.xlsx格式

时间:2014-07-31 13:50:45

标签: c# asp.net excel

public static void ExportToExcel(DataTable dtExcel, string fileName)
{
    string attachment = "attachment; filename=" + fileName + ".xlsx";
    System.Web.HttpContext.Current.Response.ClearContent();
    System.Web.HttpContext.Current.Response.AddHeader("content-disposition", attachment);
    System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    //System.Web.HttpContext.Current.Response.ContentType = "application/excel";
    //System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
    //System.Web.HttpContext.Current.Response.ContentType = string.Empty;  
    string tab = "";
    foreach (DataColumn dc in dtExcel.Columns)
    {
        System.Web.HttpContext.Current.Response.Write(tab + dc.ColumnName);
        tab = "\t";
    }
    System.Web.HttpContext.Current.Response.Write("\n");
    int i;
    foreach (DataRow dr in dtExcel.Rows)
    {
        tab = "";
        for (i = 0; i < dtExcel.Columns.Count; i++)
        {
            System.Web.HttpContext.Current.Response.Write(tab + dr[i].ToString());
            tab = "\t";
        }
        System.Web.HttpContext.Current.Response.Write("\n");
    }

    System.Web.HttpContext.Current.Response.Flush();
    System.Web.HttpContext.Current.Response.Close();

}

上面的代码片段仅生成.xls格式。如果我将响应时间和文件扩展名更改为.xlsx,则无效。是否有其他方法可以执行此操作。

根据建议我改变了方法并使用openxml库生成.xlsx。 但它抛出错误无法在生成大型xlsx文件时确定域的身份。请帮助

public static void ExportToexcel(DataTable dtExcel, string fileName)
    {
        System.Web.HttpContext.Current.Response.ClearContent();
        OpenXMLOffice openxmloffice = new OpenXMLOffice();
        MemoryStream msXML = openxmloffice.DataTableToMemoryStream(dtExcel);
        msXML.Seek(0, SeekOrigin.Begin);
        msXML.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
        System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=DataTable.xlsx");
        System.Web.HttpContext.Current.Response.StatusCode = 200;
        System.Web.HttpContext.Current.Response.Flush();
        System.Web.HttpContext.Current.Response.Close();
    }

1 个答案:

答案 0 :(得分:1)

最快最可靠的方法是使用像epplus这样的库,即使是像toDatatTable()和FromDataTable()这样的方法

http://epplus.codeplex.com/