从控制器下载Spire.doc文档到

时间:2015-05-04 12:42:06

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

我正在使用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文档返回到View,但它不能用于此。

2 个答案:

答案 0 :(得分:3)

请问您可以尝试下面的代码,让我知道它是否有效,因为我没有执行此代码但认为这应该有效,我根据您的要求修改了现有的工作代码 -

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

答案 1 :(得分:0)

将文件.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);
              
        }