0

我已经编写了导出数据的代码,但是在打开 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();
}
4

1 回答 1

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");
于 2013-02-20T12:04:54.137 回答