2013-03-27 37 views
0

是否可以使用Response.Write()保存导出的Word文档文件。现在它显示保存/打开对话框,一旦成功转换。但我需要将此文件保存到一个文件夹。请帮我解决这个问题。将导出的doc文件保存到磁盘

我的转换为Doc代码附在下面。

private void ExportDataSetToWordDoc() 
    { 
     try 
     { 
      Response.ClearContent(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", DateTime.Today.ToShortDateString().Replace("/", "").Replace("-", "") + "_" + DateTime.Now.ToShortDateString() + ".doc")); 
      Response.ContentType = "application/ms-word"; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 

      tblMain.RenderControl(htw); 


      Response.Write(sw.ToString()); 
      Response.End(); 
     } 
     catch (ThreadAbortException ex) 
     { 

      Common.LogError(ex); 
     } 

    } 
+0

您无法控制浏览器保存文件的位置。如果可以的话,想象一下恶意软件可能有多好玩...... – 2013-03-27 12:36:35

回答

1

我修改了我的代码,如下所示。现在它保存指定的文件夹

Response.ClearContent(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", DateTime.Today.ToShortDateString().Replace("/", "").Replace("-", "") + "_" + DateTime.Now.ToShortDateString() + ".doc")); 
      Response.ContentType = "application/ms-word"; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 

      tblMain.RenderControl(htw); 

      string strPath = Request.PhysicalApplicationPath + "Test.doc"; 
      StreamWriter sWriter = new StreamWriter(strPath); 
      sWriter.Write(sw.ToString()); 
      sWriter.Close(); 

谢谢。

0

您可以使用路径来使用流写入器(System.IO.StreamWriter)。 当流写入器将被关闭时,文件将被保存在指定的路径上。

但是,它会保存在服务器磁盘上。如果你想保存在客户端,你没有别的选择,而只是询问用户把文件放在哪里。未经批准,您无法将文件保存到客户端。

var x = new System.IO.StreamWriter(path); 
x.Close(); 
1

由浏览器为用户提供“打开或保存”选项。这就是你的内容处置“附加”是鼓励浏览器去做的。您的其他选项是“内联”内容处置,浏览器通常会调用应用程序(在这种情况下为Word)来打开文件。 See MSDN

不幸的是,浏览器不会总是提供您在“另存为”对话框中指定为默认文件名的文件名。相反,它通常会提供网页的名称作为默认网页。 Firefox至少把这个文件当成一个bug,IE似乎认为它是一个“功能”。