日期:2014-05-17  浏览次数:20411 次

关于word操作的问题
小弟想请教一个问题,我用Microsoft.Office.Interop.Word将服务器上一个doc文件的书签的值改了,然后我想将这个doc当模板用,在打开的地方直接把文件不保存传给客户端代码如下:
C# code
Word.Application wordApp = new Word.Application();
            object fileobj = docFileName;
            object nullobj = System.Reflection.Missing.Value;
            //打开指定文件(不同版本的COM参数个数有差异,一般而言除第一个外都用nullobj就行了)
            Word.Document doc = wordApp.Documents.Open(ref fileobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj
                );
            string strCase = string.Empty;
            foreach (Word.Bookmark BM in doc.Bookmarks)  //这是最关键的地方:对文档的任何书签进行便利匹配
            {
                strCase = BM.Name.ToString();
                switch (strCase)
                {
                    case "E_ID": //替换Advice书签的内容,其他相同
                        BM.Select();
                        BM.Range.Text = "asd";
                        break;
                }

但是怎么才能给用户提供下载呢?请指教

------解决方案--------------------
I am unable to stream a word document that I create on the fly down to the browser. I am constantly getting a message from Microsoft Word that the document is corrupt.

When I run the code via a Console Application and take ASP.NET out of the picture, the document is generated correctly with no problems. I believe everything centers around writing the file down.

Here is my code:

C# code

using (MemoryStream mem = new MemoryStream())
            {
                // Create Document
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, 
          WordprocessingDocumentType.Document, true))
                {
                    // Add a main document part. 
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                    new Document(new Body()).Save(mainPart);

                    Body body = mainPart.Document.Body;
                    body.Append(new Paragraph(
                                new Run(
                                    new Text("Hello World!"))));

                    mainPart.Document.Save();
                    // Stream it down to the browser

                    // THIS IS PROBABLY THE CRUX OF THE MATTER <---
                    Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
                    Response.ContentType = "application/vnd.ms-word.document";
                    mem.WriteTo(Response.OutputStream);
                    Response.End();
                }

            }