word2007 模板替换代码:
private void btnGenerateFinance_Click( object sender, RibbonControlEventArgs e)
{
try
{
string
thisdocFullPath =
Globals
.ThisAddIn.Application.ActiveDocument.FullName;
if
(
String
.IsNullOrEmpty(thisdocFullPath) || !System.IO.
File
.Exists(thisdocFullPath))
{
MessageBox
.Show(
"Please save current document firstly"
,
"Waring"
,
MessageBoxButtons
.OK,
MessageBoxIcon
.Warning);
return
;
}
FrmWait
.BeginWait();
string
customXML =
@"
"
;
//MessageBox.Show(customXML);
object
template = thisdocFullPath;
object
newTemplate =
false
;
object
documentType = 0;
object
visible = System.
Type
.Missing;
Document
sampledoc =
Globals
.ThisAddIn.Application.Documents.Add(
ref
template,
ref
newTemplate,
ref
documentType,
ref
visible);
object
missing = System.
Type
.Missing;
object
savePath =
Environment
.GetEnvironmentVariable(
"temp"
) +
"//"
+ sampledoc.FullName +
".docx"
;
sampledoc.SaveAs(
ref
savePath,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing);
sampledoc.ActiveWindow.Close(
ref
missing,
ref
missing);
using
(
WordprocessingDocument
wordDoc =
WordprocessingDocument
.Open(savePath.ToString(),
true
))
{
MainDocumentPart
mainPart = wordDoc.MainDocumentPart;
#region
handle repeat items
XmlDocument
customDoc =
new
XmlDocument
();
customDoc.LoadXml(customXML);
XmlDocument
doc =
new
XmlDocument
();
doc.LoadXml(mainPart.Document.Body.OuterXml);
XmlNodeList
groupList1 = doc.GetElementsByTagName(
"w:group"
);
List
<
XmlNode
> groupList =
new
List
<
XmlNode
>();
foreach
(
XmlNode
node
in
groupList1)
{
groupList.Add(node);
}
List
<
XmlNode
> removeList =
new
List
<
XmlNode
>();
int
repeatCount = 0;
foreach
(
XmlNode
node
in
groupList)
{
repeatCount = GetGroupRepeatCount(node.ParentNode.ParentNode.OuterXml, customDoc);
if
(repeatCount > 0)
{
XmlNode
groupNodeTemplate = node.ParentNode.ParentNode.CloneNode(
true
);
XmlNode
beforeNode = node.ParentNode.ParentNode;
//for (int i = 1; i <= repeatCount; i++)
for
(
int
i = repeatCount; i >= 1; i--)
{
XmlNode
newNode = groupNodeTemplate.CloneNode(
true
);
//ModifyRepeatGroup(ref newNode, i, customDoc);
GenerateRepeatGroup(
ref
newNode, i, customDoc);
beforeNode.ParentNode.InsertAfter(newNode, beforeNode);
}
removeList.Add(beforeNode);
}
}
foreach
(
XmlNode
node
in
removeList)
{
node.ParentNode.RemoveChild(node);
}
mainPart.Document.Body.InnerXml = doc.InnerXml;
mainPart.Document.Save();
#endregion
mainPart.DeleteParts<
CustomXmlPart
>(mainPart.CustomXmlParts);
//Add a new customXML part and then add content
//CustomXmlPart customXmlPart = mainPart.AddNewPart<CustomXmlPart>();
CustomXmlPart
customXmlPart = mainPart.AddCustomXmlPart(
CustomXmlPartType
.CustomXml);
//copy the XML into the new part...
using
(
StreamWriter
ts =
new
StreamWriter
(customXmlPart.GetStream()))
ts.Write(customXML);
}
//sampledoc.Activate();
sampledoc =
Globals
.ThisAddIn.Application.Documents.Open(
ref
savePath,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing,
ref
missing);
FrmWait
.EndWait();
sampledoc.Activate();
}
catch
(
Exception
ex)
{
FrmWait
.EndWait();
MessageBox
.Show(ex.Message,
"Error"
,
MessageBoxButtons
.OK,
MessageBoxIcon
.Error);
}
}
private
int
GetGroupRepeatCount(
string
groupXml,
XmlDocument
customXmlDoc)
{
groupDoc.LoadXml(groupXml);
XmlNodeList
dataList = groupDoc.GetElementsByTagName(
"w:dataBinding"
);
int
maxRepeat = 0, nodeCount;
string
path =
""
;
foreach
(
XmlNode
node
in
dataList)
{
path = node.Attributes[
"w:xpath"
].Value;
//customXmlDoc.SelectNodes(path).Item(0)
int
index;
foreach
(
XmlNode
xn
in
customXmlDoc.SelectNodes(path))
{
for
(
int
i = 0; i < xn.ParentNode.ChildNodes.Count; i++)
{
if
(xn.ParentNode.ChildNodes[i].Equals(xn))
{
index = i;
break
;
}
}
}
nodeCount = customXmlDoc.SelectNodes(path).Count;
if
(nodeCount > maxRepeat)
maxRepeat = nodeCount;
}
return
maxRepeat;
}
private
void
GenerateRepeatGroup(
ref
XmlNode
groupNode,
int
repeatIndex,
XmlDocument
customXmlDoc)
{
groupDoc.LoadXml(groupNode.OuterXml);
//w:id value must unique
XmlNodeList
idList = groupDoc.GetElementsByTagName(
"w:id"
);
string
idValue;
foreach
(
XmlNode
node
in
idList)
{
idValue = node.Attributes[
"w:val"
].Value;
node.Attributes[
"w:val"
].Value = idValue + repeatIndex.ToString();
}
XmlNodeList
dataList = groupDoc.GetElementsByTagName(
"w:dataBinding"
);
string
pathValue;
//modify xpath e.g /Customer/Item[1]/Title
foreach
(
XmlNode
node
in
dataList)
{
pathValue = node.Attributes[
"w:xpath"
].Value;
XmlNodeList
dataNodeList = customXmlDoc.SelectNodes(pathValue);
int
dataNodeCount = dataNodeList.Count;
//if this group contain not repeat data, then don't to change xpaht value
if
(dataNodeCount > 1 && repeatIndex <= dataNodeCount)
{
//pathValue = pathValue.Insert(pathValue.LastIndexOf("/"), "[" + repeatIndex.ToString() + "]");
List
<
int
> pathIndexList =
new
List
<
int
>();
CheckNodeIndex(dataNodeList[repeatIndex - 1],
ref
pathIndexList);
int
indexListLength = pathIndexList.Count;
string
[] np = pathValue.TrimStart(
new
char
[] {
'/'
}).Split(
new
char
[] {
'/'
});
for
(
int
i = 0; i < np.Length && indexListLength >= 1 + i; i++)
{
np[i] = np[i] +
"["
+ pathIndexList[indexListLength - 1 - i].ToString() +
"]"
;
}
//node.Attributes["w:xpath"].Value = pathValue;
node.Attributes[
"w:xpath"
].Value =
"/"
+
string
.Join(
"/"
, np);
}
}
groupNode.InnerXml = groupDoc.InnerXml;
}
protected
void
CheckNodeIndex(
XmlNode
checkNode,
ref
List
<
int
> indexList)
{
int
index = 0;
if
(checkNode.ParentNode !=
null
)
{
foreach
(
XmlNode
node
in
checkNode.ParentNode.ChildNodes)
{
if
(node.Name.Equals(checkNode.Name) && node != checkNode)
{
index++;
}
else
if
(node == checkNode)
{
index++;
break
;
}
}
indexList.Add(index);
CheckNodeIndex(checkNode.ParentNode,
ref
indexList);
}
}
private
XmlDocument
groupDoc =
new
XmlDocument
();