【问题标题】:Downloading Spire.doc document from controller to view从控制器下载 Spire.doc 文档以查看
【发布时间】:2015-05-04 12:42:05
【问题描述】:

我正在使用 Spire.doc 创建 Word 文件,我按照他们的示例进行操作

public class WordController : Controller
{
    public void Download()
    {
        Document doc = new Document();

        Paragraph test = doc.AddSection().AddParagraph();

        test.AppendText("This is a test");

        doc.SaveToFile("Doc.doc");

        try
        {
            System.Diagnostics.Process.Start("Doc.doc");
        }catch(Exception)
        {

        }
    }
}

这会在 Microsoft Word 中打开 Word 文件,但我怎样才能让它被下载呢?

我之前使用return File() 将PDF 文档返回到视图,但它不适用于此。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 model-view-controller spire.doc


    【解决方案1】:

    您能否尝试以下代码并告诉我它是否有效,因为我没有执行此代码但相信这应该有效,我根据您的要求修改了我现有的工作代码-

            public class WordController : Controller
            {
                public void Download()
                {
                    byte[] toArray = null;
                    Document doc = new Document();
                    Paragraph test = doc.AddSection().AddParagraph();
                    test.AppendText("This is a test");
                    using (MemoryStream ms1 = new MemoryStream())
                    {
                        doc.SaveToStream(ms1, FileFormat.Doc);
                        //save to byte array
                        toArray = ms1.ToArray();
                    }
                    //Write it back to the client
                    Response.ContentType = "application/msword";
                    Response.AddHeader("content-disposition", "attachment;  filename=Doc.doc");
                    Response.BinaryWrite(toArray);
                    Response.Flush();
                    Response.End();
                }
            }
    

    【讨论】:

      【解决方案2】:

      将文件 .docx 加载到 richtextbox.rtf(使用 Spire.Doc):

             byte[] toArray = null;
      
             //Paragraph test = doc.AddSection().AddParagraph();
             //test.AppendText("This is a test") --> this also works ;
      
              Document doc = new Document();
              doc.LoadFromFile("C://Users//Mini//Desktop//doc.docx");
      
             // or - Document doc = new Document("C://Users//Mini//Desktop//doc.docx");
      
              using (MemoryStream ms1 = new MemoryStream())
              {
                  doc.SaveToStream(ms1, FileFormat.Rtf);
                  toArray = ms1.ToArray();
                  richTextBox1.Rtf = System.Text.Encoding.UTF8.GetString(toArray);
                    
              }
      

      【讨论】:

        猜你喜欢
        • 2017-10-30
        • 1970-01-01
        • 2012-08-19
        • 2019-03-18
        • 1970-01-01
        • 2015-01-11
        • 1970-01-01
        • 1970-01-01
        • 2013-03-19
        相关资源
        最近更新 更多