Export to word with a filename doesn't seem to work

别等时光非礼了梦想. 提交于 2019-12-13 00:10:22

问题


I export a datatable to word, when I pass a file name it doesn't seem to get the file name in Open/Save dialog box.

Here is what I am doing

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;
    }
}

When I pass filename "report(" + System.DateTime.Now.ToString("dd/MM/yyyy"); + ")" it doesn't take the value as dd/MM/YYYY instead it shows file name as dd_MM_YYYY


回答1:


Few remarks about your code:

  1. You are setting the content type header to a word document but you are actually sending HTML contents by rendering a GridView
  2. dd/MM/YYYY is not a valid filename because of the / character.
  3. You don't need a try/catch block if in the catch statement you are only doing throw err
  4. Calling Response.End at the end is not necessary.
  5. Always use using statement when dealing with disposable objects such as streams and readers/writers to ensure that the Dispose method is invoked in all cases.



回答2:


You should to use a filename like

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



回答3:


A filename cannot have "/".




回答4:


That's most likely because / isn't a valid character for filenames. Your name must fulfill certain criteria, be sure not to use any of

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




回答5:


If you have forward slashes in the filename, I would assume that this would break the URL to the file and hence the slashes are being replaced at some point?



来源:https://stackoverflow.com/questions/1973843/export-to-word-with-a-filename-doesnt-seem-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!