我在我的程序上运行时生成了一个XML文件。这个XMLfile.InnerText()有一些格式(如-enter,空格,制表符,Alignments),如下所示,
这是对windows驱动程序的测试
2115 -XXXXXXXXXX BRANCH XXXX
XXXXXXXXXX XXXXXXXXXX
XXXXXXXXXX XX
XXXXXXXXXX:08/23/16 XXX XXX:
08/23/19 XXXXXXXX XXXXXX:9
XXXXXX XXX X.
XXXX:XXX 0,01
XXXXXX XXX
XXXXX:1
我正在尝试使用VB.net使用此XMLfile.InnerText(使用上面的格式和对齐)创建一个word文档(提供使用的代码作为示例)。
Dim vWordDoc As WordprocessingDocument = WordprocessingDocument.Create(tmppath, WordprocessingDocumentType.Document)
' Set the content of the document so that Word can open it.
Dim vMainPart As MainDocumentPart = vWordDoc.AddMainDocumentPart()
' Create the document structure and add some text.
vMainPart.Document = New Document()
Dim vBody As Body = vMainPart.Document.AppendChild(New Body())
Dim vPara As Paragraph = vBody.AppendChild(New Paragraph())
Dim run As Run = vPara.AppendChild(New Run())
run.AppendChild(New Text(XMLFile.InnerText))
vMainPart.Document.Save()
vWordDoc.Close()
通过使用Microsoft.Office.Interop.Word.Application -> Range.InsertXML()
方法,我能够在word文件中使用相同的格式。
但我想通过使用OpenXML方法在我新创建的word文件中捕获相同的XML格式?
Word UI /经典对象模型在Word应用程序中未打开时直接处理文件内容时自动执行许多不可用的操作。 InsertXML
基本上执行XML到Word内容的转换。 Open XML SDK中没有直接的等价物。
Open XML SDK的功能是AlternativeFormatImportPart,AlternativeFormatImportPartType Enum和altChunk。
根据Enum文档,XML是此方法的有效文件格式。结果是否与InsertXML
相同,你必须测试。 altChunk链接包含可用于起点的示例代码,我在此处复制以供参考。
using System.Linq;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace altChunk
{
class Program
{
static void Main(string[] args)
{
string fileName1 = @"c:\Users\Public\Documents\Destination.docx";
string fileName2 = @"c:\Users\Public\Documents\Source.docx";
string testFile = @"c:\Users\Public\Documents\Test.docx";
File.Delete(fileName1);
File.Copy(testFile, fileName1);
using (WordprocessingDocument myDoc =
WordprocessingDocument.Open(fileName1, true))
{
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk =
mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = File.Open(fileName2, FileMode.Open))
chunk.FeedData(fileStream);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainPart.Document
.Body
.InsertAfter(altChunk, mainPart.Document.Body
.Elements<Paragraph>().Last());
mainPart.Document.Save();
}
}
}
}
这种方法的作用是将外部内容存储为ZIP包的一部分。 Word打开文件时,它执行转换,将内容集成到Word文档中。在此过程中删除存储的内容。