我尝试了网站中提到的一些解决方案,例如Using System.Microsoft.Office.Excel
and Excel = System.Microsoft.Office.Excel
,但它不起作用....在这里,我试图获取表格中的数据并以 .xls 格式下载到服务器中指定位置的文件和然后给用户一个下载文件的链接。这是导出的代码`
protected void btnExcelExport_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using( HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// get gridlines from gridview
table.GridLines = GridView2.GridLines;
if (GridView2.HeaderRow != null)
{
table.Rows.Add(GridView2.HeaderRow);
}
foreach (GridViewRow row in GridView2.Rows)
{
table.Rows.Add(row);
}
if (GridView2.FooterRow != null)
{
table.Rows.Add(GridView2.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
}
var myRootPath = Server.MapPath("~");
var docPath = Path.GetFullPath(Path.Combine(myRootPath, "/Compare/c.xls"));
File.WriteAllText(docPath, sw.ToString());
}
dwndlink.Visible = true;
}
当这是链接按钮的代码时:
protected void dwnlink(object sender, EventArgs e)
{
var webRootPath = Server.MapPath("~");
var docPath = Path.GetFullPath(Path.Combine(webRootPath, "/Compare/c.xls"));
string name = Path.GetFileName(docPath);
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
Response.ContentType = "Application/vnd.ms-excel";
Response.TransmitFile(docPath);
Response.End();
}
因此,当用户打开下载的文件时,会发出警告,因为它不在同一个扩展名中。为什么会出现这种情况..??
我尝试使用各个站点提供的解决方案,但无济于事...
谢谢