导出Asp.net Gridview到Excel错误消息

时间:2015-11-27 05:34:35

标签: c# asp.net excel gridview export-to-excel

我正在使用RenderControl将Excel格式导出为Excel。下面的方法是代码的一部分。

gridExcel.HeaderRow.BackColor = System.Drawing.Color.FromArgb(0, 255, 255, 204);
gridExcel.HeaderRow.Font.Bold = false;
gridExcel.HeaderRow.Height = Unit.Pixel(30);

StringWriter sw = new StringWriter();
gridExcel.RenderControl(new HtmlTextWriter(sw));

string renderedGridView = sw.ToString();

//filename will be like xyz.xls

System.IO.File.WriteAllText(@filename, renderedGridView);

它成功创建了excel文档但是当这个文档从网站下载并且用户从下载文件夹打开它时,每次s \他得到下面提到的错误但用户都能打开文档。

enter image description here

任何人都可以建议可以采取哪些措施来避免这个问题。

2 个答案:

答案 0 :(得分:1)

<强>原因

  1. 这是因为在传统的Export to Excel方法中,GridView首先转换为HTML字符串,然后将该HTML字符串导出到Excel。因此,最初它不是Excel文件,因此Excel应用程序抛出警告/错误“您尝试打开的文件格式与文件扩展名指定的格式不同。”
  2. 此类导出的Excel文件只能用于显示目的,您不能将其用于通常可在有效Excel文件中执行的Excel操作。

    摘自here

    <强>解

    您应该使用CLOSEXML来解决它。

    public static void ExportToExcel(IEnumerable<dynamic> data, string sheetName)
    {
      /****** YOUR ORIGINAL CODE *******/
    
        gridExcel.HeaderRow.BackColor = System.Drawing.Color.FromArgb(0, 255, 255, 204);
        gridExcel.HeaderRow.Font.Bold = false;
        gridExcel.HeaderRow.Height = Unit.Pixel(30);
        StringWriter sw = new StringWriter();
        gridExcel.RenderControl(new HtmlTextWriter(sw));
    
        string renderedGridView = sw.ToString();
    
        //filename will be like xyz.xls
        System.IO.File.WriteAllText(@filename, renderedGridView);
    
    
    
        /**************** Set it accordingly by below reference ****************************/
        XLWorkbook wb = new XLWorkbook();
        var ws = wb.Worksheets.Add(sheetName);
        ws.Cell(2, 1).InsertTable(data);
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
    
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);
            memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
            memoryStream.Close();
        }
    
        HttpContext.Current.Response.End();
    
    }
    

    代码参考来自HERE

答案 1 :(得分:0)

您可以尝试这种方法

    gridExcel.HeaderRow.BackColor = System.Drawing.Color.FromArgb(0, 255, 255, 204);
    gridExcel.HeaderRow.Font.Bold = false;
    gridExcel.HeaderRow.Height = Unit.Pixel(30);
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename="@filename+".xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    gridExcel.RenderControl(new HtmlTextWriter(sw));
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();