用 DocumentFormat.OpenXml 和Microsoft.Office.Interop.Word 写入或者读取word文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace MediaTools.Tool
{
    public class WordHelper
    {
        public static void TxtToword(string docPath, string txtPath)
        {
            var txtContent = File.ReadAllText(txtPath, Encoding.UTF8);
            WriteToWord(docPath, txtContent);
        }
        public static void WriteToWord(string docPath, string content)
        {
            if (!File.Exists(docPath)) CreateWordprocessingDocument(docPath);
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(docPath);
            object missing = System.Reflection.Missing.Value;
            doc.Content.Text = content;
            app.Visible = false;
            doc.Save();
            doc.Close();
        }

        private static void CreateWordprocessingDocument(string filepath)
        {
            // Create a document by supplying the filepath.
            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add a main document part.
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                // Create the document structure and add some text.
                mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                Body body = mainPart.Document.AppendChild(new Body());
                DocumentFormat.OpenXml.Drawing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Drawing.Paragraph());
                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text(""));
            }
        }

        public static string GetContentFromWord(string docPath)
        {
            const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

            StringBuilder textBuilder = new StringBuilder();
            using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(docPath, false))
            {
                NameTable nt = new NameTable();
                XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
                nsManager.AddNamespace("w", wordmlNamespace);
                XmlDocument xdoc = new XmlDocument(nt);
                xdoc.Load(wdDoc.MainDocumentPart.GetStream());

                XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager);

                foreach (XmlNode paragraphNode in paragraphNodes)
                {
                    //XmlNodeList textNodes = paragraphNode.SelectNodes(".//[‘w: t‘&‘w:tab‘]", nsManager);
                    XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsManager);

                    foreach (System.Xml.XmlNode textNode in textNodes)
                    {
                        textBuilder.Append(textNode.InnerText);
                    }
                    textBuilder.Append(Environment.NewLine);
                }
            }
            var result = textBuilder.ToString();
            return result;
        }
    }
}

原文地址:https://www.cnblogs.com/dayang12525/p/10268244.html

时间: 2024-07-29 23:57:15

用 DocumentFormat.OpenXml 和Microsoft.Office.Interop.Word 写入或者读取word文件的相关文章

无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”。

无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”.此操作失败的原因是对 IID 为“{00020970-0000-0000-C000-000000000046}”的接口的 COM 组件调用 QueryInterface 因以下错误而失败: 加载类型库/DLL 时出错. (异常来自 HRESULT:0x80029C4A

VS编程中找不到Microsoft.Office.Core、Microsoft.Office.Interop.Word和VBIDE

在使用vs2005. vs2008. vs2010 制作包含 word等office的应用程序时,有时找不到对Microsoft.Office.Core. Microsoft.Office.Interop.Word和VBIDE 三个文件的引用,此时,如果已经安装了office 2003,那么可能是选择“典型安装”或者是“最小化安装”,那需要从“控制面板”中将其删除,然后再次安装,并选择“完全安装”,安装之后再使用以下两 种方法之一即可. 在选择“完全安装”office 2003 后,使用以下两种

2015.5.21 VS2010中引用Word组件后提示 类型“Microsoft.Office.Interop.Word.ApplicationClass”未定义构造函数 解决方法

wordApp = new Word.ApplicationClass();//这句在VS2005中没问题,在2010中会报错. 解决方法:在资源管理器 "引用"项的"Microsoft.Office.Interop.Word" 上点击鼠标右键,选择"属性",将属性中的"嵌入互操作类型"的值改为"false"即可.  这项在vs2005中没有

System.InvalidCastException: 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”。

报错:System.InvalidCastException: 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”.此操作失败的原因是对 IID 为“{00020970-0000-0000-C000-000000000046}”的接口的 COM 组件调用 QueryInterface 因以下错误而失败: 加载类型库/D

Microsoft.Office.Interop.Word 创建word

Microsoft.Office.Interop.Word 创建word 转载:http://www.cnblogs.com/chenbg2001/archive/2010/03/14/1685746.html 功能总结或者完善. 一.添加页眉 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System

错误类型“Microsoft.Office.Interop.Word.ApplicationClass”未定义构造函数

原文网址:http://zhidao.baidu.com/link?url=WcvaYFI1JeEGvbjD77nDbGp21sjaNCnCTRLGrU5YjwUGbHbhHJxQolKbsMZbZsLr8R5K0IGGKj8IbPkERucU7NThRXcbIdq5hl90nWdtLYe 解决办法:解决方案资源管理器 -> 引用 -> "Microsoft.Office.Interop.Word" -> 右键选择属性 -> 嵌入互操作类型的值改为"f

类型“Microsoft.Office.Interop.Word.ApplicationClass”未定义构造函数

错误 4317 无法嵌入互操作类型“Microsoft.Office.Interop.Word.ApplicationClass”.请改用适用的接口. 类型“Microsoft.Office.Interop.Word.ApplicationClass”未定义构造函数 解决办法: 在Visual Studio 中点击菜单项“视图->解决方案资源管理器”,在其中点开“引用”文件夹,在"Microsoft.Office.Interop.Word" 上点击鼠标右键,选择“属性”,将属性中

Could not load file or assembly 'Microsoft.Office.Interop.Word, Version=14.0

参考地址一:点击这里 参考地址二:点击这里 解决方法: 使用office COM元件,电脑里必须要有相对应的版本,比如 Excel 14.0是对应Excel 2010 Excel 12.0是对应Excel 2007 Excel 11.0是对应Excel 2003 使用Excel COM必须要注意版本问题,并非用最高版本就能操作低版本. Could not load file or assembly 'Microsoft.Office.Interop.Word, Version=14.0

Microsoft.Office.Interop.Word.DocumentClass.SaveAs 命令失败

asp.net 常用的生成word功能,代码也是网上常见的,自己本地反复测试过没问题.serves 2003下运行没问题,可是发布到2008上就出错.组件权限已配置,windows目录下temp权限已给,程序目录权限已给,也加入了<identity impersonate="true" userName="administrator" password="XXXXX"/>,连administrator的用户控制都关了. 保存word文