public partial class WordprocessingDoc
{
private PackageHelper package;
public PackageHelper Package
{
get { return package; }
set { package = value; }
}
public WordprocessingDoc()
{
//Properties.Resources.BaseWordDocument为已经添加到资源中的一个空洞docx文档,这里也
package = new PackageHelper(Properties.Resources.BaseWordDocument);
}
public WordprocessingDoc(string strTempFile)
{
//用一个已经存在的文件
package = new PackageHelper( FileHelper.ReadFile(strTempFile));
}
#region Insert Text
//插入文字
public void WriteText(XmlWriter writer, string inputString, string styleName, bool newParagraph)
{
//如果需要另起一段,添加相关标记
if(newParagraph) writer.WriteStartElement(Prefixes.WordprocessingML, "p", Namespaces.WordprocessingML);
//设置当前段落的样式ID,为空则不处理
if (styleName != "") ApplyParagraphStyle(writer, styleName);
writer.WriteStartElement(Prefixes.WordprocessingML, "r",
Namespaces.WordprocessingML);
writer.WriteElementString(Prefixes.WordprocessingML, "t",
Namespaces.WordprocessingML, inputString);
writer.WriteEndElement();
if(newParagraph) writer.WriteEndElement();
}
#endregion
}
使用上面的类
public static void Run()
{
PackageHelper package;
WordprocessingDoc xmlDoc = new WordprocessingDoc();
package = xmlDoc.Package;
Uri documentUri =
new Uri(@"/word/document.xml", UriKind.Relative);
XmlDocument documentXml =
package.GetWritablePart(documentUri);
XPathNavigator documentNav = documentXml.CreateNavigator().SelectSingleNode("w:document/w:body/w:p", Namespaces.NamespaceManager);
using (XmlWriter writer = documentNav.ReplaceRange(documentNav))
{
xmlDoc.WriteText(writer, "2008-2-20 -2008-2-26","MySubTitle");
}
}