一、WordprocessingML 1、文档结构 2、元素 Document,Body,Paragraph,Run,Text 3、编程 const string wordprocessingML = @"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const string mainContentType = @"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"; const string mainRelationship = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; public static void CreateWordDocument(string fileName, string bodyText) { // 主部件 Document XmlDocument xmlStartPart = new XmlDocument(); XmlElement tagDocument = xmlStartPart.CreateElement("w:document", wordprocessingML); xmlStartPart.AppendChild(tagDocument); // 文档主体 Body XmlElement tagBody = xmlStartPart.CreateElement("w:body", wordprocessingML); tagDocument.AppendChild(tagBody); // 定义段 Paragraph XmlElement tagParagraph = xmlStartPart.CreateElement("w:p", wordprocessingML); tagBody.AppendChild(tagParagraph); // 定义范围 Run XmlElement tagRun = xmlStartPart.CreateElement("w:r", wordprocessingML); tagParagraph.AppendChild(tagRun); // 文字 XmlElement tagText = xmlStartPart.CreateElement("w:t", wordprocessingML); tagRun.AppendChild(tagText); // 插入文字 XmlNode nodeText = xmlStartPart.CreateNode(XmlNodeType.Text, "w:t", wordprocessingML); nodeText.Value = bodyText; tagText.AppendChild(nodeText); // 创建包 Package pkgOutputDoc = null; pkgOutputDoc = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite); // 保存主部件 Uri uri = new Uri("/word/document.xml", UriKind.Relative); PackagePart partDocumentXML = pkgOutputDoc.CreatePart(uri, mainContentType); StreamWriter streamStartPart = new StreamWriter(partDocumentXML.GetStream(FileMode.Create, FileAccess.Write)); xmlStartPart.Save(streamStartPart); streamStartPart.Close(); pkgOutputDoc.Flush(); // 创建关系部件 pkgOutputDoc.CreateRelationship(uri, TargetMode.Internal, mainRelationship, "rId1"); // 保存、关闭流 pkgOutputDoc.Flush(); pkgOutputDoc.Close(); } public static void CreateWordDocument2(string fileName, string bodyText) { using (WordprocessingDocument wdDoc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = wdDoc.AddMainDocumentPart(); mainPart.Document = new Document(new Body()); Paragraph para = new Paragraph(new Run(new Text(bodyText))); mainPart.Document.Body.AppendChild<Paragraph>(para); } }