【问题标题】:Export to word with a filename doesn't seem to work导出到带有文件名的单词似乎不起作用
【发布时间】:2009-12-29 10:06:00
【问题描述】:

我将数据表导出为 word,当我传递文件名时,它似乎没有在打开/保存对话框中获取文件名。

这就是我正在做的事情

public static void Convertword(DataTable dt, HttpResponse Response,string filename)
{
    try
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc");
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.word";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
        System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
        dg.DataSource = dt;
        dg.DataBind();
        dg.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    catch(Exception err)
    {
        throw err;
    }
}

当我传递文件名 "report(" + System.DateTime.Now.ToString("dd/MM/yyyy"); + ")" 时,它不会将值设为 dd/MM/YYYY,而是将文件名显示为 dd_MM_YYYY

【问题讨论】:

  • 所以问题是文件保存对话框显示“dd_MM_yyyy”而不是“dd/MM/yyyy”,或者问题是它显示了其他内容(如 mypage.aspx ...)?如果你想发送一个实际的 Word 文件,你应该使用一些库来编写 Word 文件并写入响应输出流(即发送字节)

标签: asp.net filenames export-to-word


【解决方案1】:

关于您的代码的几点说明:

  1. 您正在将内容类型标头设置为 word 文档,但您实际上是通过呈现 GridView 来发送 HTML 内容
  2. 由于/ 字符,dd/MM/YYYY 不是有效的文件名。
  3. 如果在catch 语句中您只在执行throw err,则不需要try/catch
  4. 不需要最后调用Response.End
  5. 在处理流和读取器/写入器等一次性对象时始终使用using 语句,以确保在所有情况下都调用Dispose 方法。

【讨论】:

  • 除了第 3 点:throw err; 是不好的做法,因为它删除了调用堆栈。如果您想重新抛出异常,只需使用throw;
  • 我将 Response.End 替换为 HttpContext.Current.ApplicationInstance.CompleteRequest();
  • 除了第 1 点之外:这实际上可行,尽管它可能看起来错误(尝试将 .html 文件重命名为 .doc,它将在 Word 中打开)。
【解决方案2】:

你应该使用类似的文件名

String.Format("report{0:ddMMyyyy}.doc", DateTime.Now);

【讨论】:

    【解决方案3】:

    文件名不能有“/”。

    【讨论】:

      【解决方案4】:

      这很可能是因为/ 不是文件名的有效字符。你的名字必须满足一定的条件,一定不要使用任何

      * . " / \ [ ] : ; | = ,

      【讨论】:

        【解决方案5】:

        如果文件名中有正斜杠,我认为这会破坏文件的 URL,因此斜杠会在某个时候被替换?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-12
          相关资源
          最近更新 更多