导出的excel文件保存为网页
本文关键字:保存 网页 文件 excel | 更新日期: 2023-09-27 17:51:09
当我通过c#代码编辑并保存导出的Excel文件时,它将保存为网页:
static String ISO_Date()
{
return DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
}
protected void lnkbtnExport_Click(object sender, EventArgs e)
{
if (grdView.Rows.Count > 0)
{
logger.logTrace("Exporting branch details to excel", Session["UserID"] == null ? 0 : Convert.ToInt32(Session["UserID"]));
pBindData(null, true);
grdView.DataSource = ViewState["DataBind"];
grdView.DataBind();
ExportGridView();
pExportGridToExcel(grdView, "Location_Details_" + Convert.ToString(DateTime.Now) + ".xls");
}
}
private void ExportGridView()
{
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
// Render grid view control.
grdView.RenderControl(htw);
// Write the rendered content to a file.
string renderedGridView = sw.ToString();
string path = System.Configuration.ConfigurationSettings.AppSettings["ExportedExcel"].ToString();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
System.IO.File.WriteAllText(path + "_" + ISO_Date() + "_" + FromDate.Replace("/", "-") + "_" + ToDate.Replace("/", "-") + ".xls", renderedGridView);
}
private void pExportGridToExcel(GridView grdGridView, String fileName)
{
Response.Clear();
Response.AddHeader("content-disposition",
String.Format("attachment;filename={0}", fileName));
Response.Charset = "";
Response.ContentType = "application/ms-excel";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
ClearControls(grdView);
grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString().Replace(HttpUtility.HtmlDecode(" "), " "));
Response.End();
}
这些是我用来导出到excel的函数。它是导出但是当我打开同样的excel并尝试保存它时它保存为网页格式
你能试试这段代码吗:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
this.BindGrid();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}