从gridview导出后打开excel文件时出现警告消息

时间:2013-02-20 11:52:52

标签: c# asp.net

我已经编写了导出数据的代码,但是在打开excel文件时我正面临警告消息,默认情况下文件保存为.html扩展名

警告 - “您打开的文件格式与文件扩展名指定的格式不同”

我需要保存.xls扩展名 请帮帮我

  private void ExportToExcel(DataTable dt)
  {
 string fileName = "FileName" + DateTime.Now.ToString("MMddyyyy_HHmmss") + ".xls";

        Response.AddHeader("content-disposition", "attachment;filename=" + fileName);

        //Response.AddHeader("content-disposition", "attachment;filename=Filename .xls");
        Response.ContentType = "application/vnd.ms-excel";

        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
        DataGrid dataExportExcel = new DataGrid();
        dataExportExcel.ItemDataBound += new DataGridItemEventHandler(dataExportExcel_ItemDataBound);
        dataExportExcel.DataSource = dt;
        dataExportExcel.DataBind();
        dataExportExcel.RenderControl(htmlWrite);
        System.Text.StringBuilder sbResponseString = new System.Text.StringBuilder();
        sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:xlExcel8\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head></head> <body>");
        sbResponseString.Append(stringWriter + "</body></html>");
        Response.Write(sbResponseString.ToString());
        Response.End();
}

1 个答案:

答案 0 :(得分:0)

使用此选项 - http://www.gemboxsoftware.com/spreadsheet/overview

看起来像这样使用:

// Create new Excel file.
var excelFile = new ExcelFile();

excelFile.Worksheets.Add(dt.TableName).InsertDataTable(dt, 0, 0, true);

// Save Excel file to XLS format.
excelFile.SaveXls(dataSet.DataSetName + ".xls");