我有一个将数据导出到 excel 文件的网页。我遇到的唯一问题是,当我尝试打开 excel 文件时,我收到一条消息,提示“您尝试打开的文件的格式与文件扩展名指定的格式不同。验证文件没有损坏并且来自在打开文件之前受信任的来源。”。我怎样才能摆脱这个消息。为了进行导出,我使用了我在另一篇文章中找到的函数。这是代码...
private void ExporttoExcel(DataTable table)
{
//Response.Clear();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/excel";
HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=TestingReports");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1252");
// Sets font
HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
HttpContext.Current.Response.Write("<BR><BR><BR>");
// Sets the table border, cell spacing, border color, font of the text, background, foreground, font height
HttpContext.Current.Response.Write("<Table bgColor='#ffffff' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
// Am getting my grid's column headers
int columnscount = table.Columns.Count;
// Write in new column
for (int j = 0; j < columnscount; j++)
{
HttpContext.Current.Response.Write("<Td style='font-size:15.0pt; text-align:center; width:80.0pt; border-width:1.0pt; border-color:#000000; border-style:solid; height:22.0pt;'>");
// Get column headers and make it as bold in excel columns
HttpContext.Current.Response.Write("<B>");
HttpContext.Current.Response.Write(table.Columns[j].ToString());
HttpContext.Current.Response.Write("</B>");
HttpContext.Current.Response.Write("</Td>");
}
HttpContext.Current.Response.Write("</TR>");
// Write in new row
foreach (DataRow row in table.Rows)
{
HttpContext.Current.Response.Write("<TR>");
for (int i = 0; i < table.Columns.Count; i++)
{
HttpContext.Current.Response.Write("<Td style='width:80.0pt; text-align:center; border-width:0.5pt; border-color:#000000; border-style:solid; height:22.0pt;'>");
HttpContext.Current.Response.Write(row[i].ToString());
HttpContext.Current.Response.Write("</Td>");
}
HttpContext.Current.Response.Write("</TR>");
}
HttpContext.Current.Response.Write("</Table>");
HttpContext.Current.Response.Write("</font>");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//Response.Write("TestingReports.xls");
//Response.Flush();
//Response.End();
}
任何帮助都感激不尽。先感谢您。