原来我遇到的问题是我的代码和示例实际上并没有删除位于“CustomXML”文件夹中的以前的 CustomXMLParts。我的代码以两种方式工作,第一种是带有一个按钮 (btnGenerate) 的 Windows 窗体应用程序,它允许您选择 template.docx 和 customXML.xml 文件。第二个是控制台程序。欢呼
Windows 窗体应用程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.Threading;
namespace TestReportCreator_Beta
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[STAThread]
private void btnGenerate_Click(object sender, EventArgs e)
{
string outFile = @"C:\Users\Christopher\Desktop\BookData\TestReportBetaEND.docx";
OpenFileDialog OFD = new OpenFileDialog();
OFD.Multiselect = false;
OFD.Title = "Open Word Document";
OFD.Filter = "Word Document|*.docx;*.domx";
OFD.ShowDialog();
string docPath = OFD.FileName;
OFD.Title = "Opne Xml Document";
OFD.Filter = "Xml Document|*.xml";
OFD.ShowDialog();
string xmlPath = OFD.FileName;
// convert template to document
File.Copy(docPath, outFile);
using (WordprocessingDocument doc = WordprocessingDocument.Open(outFile, true))
{
MainDocumentPart mdp = doc.MainDocumentPart;
if (mdp.CustomXmlParts != null)
{
mdp.DeleteParts<CustomXmlPart>(mdp.CustomXmlParts);
}
CustomXmlPart cxp = mdp.AddCustomXmlPart(CustomXmlPartType.CustomXml);
FileStream fs = new FileStream(xmlPath, FileMode.Open);
cxp.FeedData(fs);
mdp.Document.Save();
}
}
}
}
这是控制台程序版本
using System; using System.Collections.Generic;
using System.Linq; using System.Text;
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing; using System.IO;
namespace BookData
{
class Program
{
static void Main(string[] args)
{
string template = @"C:\Users\Christopher\Desktop\BookData\TestReportBeta.docx";
string outFile = @"C:\Users\Christopher\Desktop\BookData\TestReportBetaEND.docx";
string xmlPath = @"C:\Users\Christopher\Desktop\BookData\TestReport.xml";
// convert template to document
File.Copy(template, outFile);
using (WordprocessingDocument doc = WordprocessingDocument.Open(outFile, true))
{
MainDocumentPart mdp = doc.MainDocumentPart;
if (mdp.CustomXmlParts != null)
{
mdp.DeleteParts<CustomXmlPart>(mdp.CustomXmlParts);
}
CustomXmlPart cxp = mdp.AddCustomXmlPart(CustomXmlPartType.CustomXml);
FileStream fs = new FileStream(xmlPath, FileMode.Open);
cxp.FeedData(fs);
mdp.Document.Save();
}
}
}
}
我希望你们那里的开发人员和办公自动化人员能够很好地利用它!