【问题标题】:Prevent download when exporting Gridview to Excel将 Gridview 导出到 Excel 时阻止下载
【发布时间】:2014-05-19 08:42:52
【问题描述】:



我正在尝试将 Gridview 中的数据导出到 Excel 并将该文件存储在服务器上的文件夹中。
我已经完成了这部分。我唯一想做的就是,
我想阻止下载 Excel 文件。
请在下面找到我的代码。

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "order.xls"));
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gridX.AllowPaging = false;
    bindX();
    gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
    for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
    {
        gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
    }
    gridX.RenderControl(htw);
    //Response.Write(sw.ToString());
    string renderedGridView = sw.ToString();
    string path = Server.MapPath("~/Order/od/x");
    System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
    sw.Close();
    htw.Close();


提前致谢。

【问题讨论】:

  • 这意味着您只想将此文件显示为临时文件?
  • 或者你可以说你想在网页中显示excel文件?
  • 我只想将文件保存在一个文件夹中。
  • ok,这意味着你想将文件直接保存在用户机器的特定文件夹中。但据我所知,您必须先下载文件。

标签: asp.net


【解决方案1】:

根据需要编辑使用此代码:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    e.Cancel = true;
    WebClient client = new WebClient();

    client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);

    client.DownloadDataAsync(e.Url);
}

void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    string filepath = textBox1.Text;
    File.WriteAllBytes(filepath, e.Result);
    MessageBox.Show("File downloaded");
}

希望这会对你有所帮助。

【讨论】:

    【解决方案2】:

    我得到了答案。

    代码

    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gridX.AllowPaging = false;
    bindX();
    gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
    for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
    {
       gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
    }
    gridX.RenderControl(htw);
    //Response.Write(sw.ToString());
    string renderedGridView = sw.ToString();
    string path = Server.MapPath("~/Order/od/x");
    System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
    sw.Close();
    htw.Close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      • 1970-01-01
      相关资源
      最近更新 更多