我有一个在运行时生成的XML文件,在我的program.This XMLfile.InnerText()上有一些格式(如-enter,空格,制表符,对齐),如下所示。
这是对windows驱动程序的测试。
2115 -XXXXXXXXXX分支机构XXXX
XXXXXXXXXX
XXXXXXXXXX XX
XXXXXXXXXX : 08/23/16 XXX XXX:
08/23/19 XXXXXXXX XXXXXX :9
XXXXXX XXX X
XXXX: XXXX 0,01
XXX XXX XXX
XXXXX:1
XXXXXXXXX
我正在尝试使用VB.net(以使用的代码为例)创建一个word文档与此XMLfile.InnerText(与上面的格式和对齐)。
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格式?
发布于 2019-03-13 06:34:47
当文件内容在Word应用程序中未打开时,Word UI/经典对象模型会自动执行许多操作,而这些操作在直接处理文件内容时不可用。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文档中。在该过程中删除所存储的内容。
https://stackoverflow.com/questions/55118745
复制相似问题