簡體   English   中英

導出為帶文件名的單詞似乎不起作用

[英]Export to word with a filename doesn't seem to work

我將數據表導出到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

關於您的代碼的幾點評論:

  1. 您正在將內容類型標題設置為word文檔,但實際上是通過呈現GridView發送HTML內容
  2. 由於/字符, dd/MM/YYYY不是有效的文件名。
  3. 如果在catch語句中僅執行throw err則不需要try/catch
  4. 不需要最后調用Response.End
  5. 處理流和讀取器/寫入器等一次性對象時,請始終使用using語句,以確保在所有情況下均調用Dispose方法。

您應該使用類似的文件名

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

文件名不能包含“ /”。

這很可能是因為/不是文件名的有效字符。 您的姓名必須符合某些條件,請確保不要使用任何

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

如果文件名中包含正斜杠,我會認為這會破壞文件的URL,因此在某些時候會替換斜杠?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM