private void btnDox_Click(object sender, EventArgs e)
{
DocX docx = new DocX();
docx.Load(@"D:\Test.docx");
docx.ReplaceText("$Name$", "你好", "標楷體", System.Drawing.Color.Red);
docx.ReplaceText("$Name1$", "大家好", "標楷體", System.Drawing.Color.Green);
docx.SaveAs(@"D:\Output.docx");
}
public class DocX {
private string _xmlString;
private string _xmlOutputString;
private WordprocessingDocument _Templateword;
private Document _Outputdoc;
private Dictionary<string, Run> _dic;
public DocX() {
_xmlString = string.Empty;
_Outputdoc = null;
_dic = new Dictionary<string, Run>();
}
public void Load(string Templatefile)
{
_xmlString = string.Empty;
_xmlOutputString = string.Empty;
_Outputdoc = null;
_Templateword = WordprocessingDocument.Open(Templatefile, true);
_Outputdoc = _Templateword.MainDocumentPart.Document;
_Templateword.Close();
_xmlString = _Outputdoc.InnerXml;
}
private void GetRunList() {
_dic = new Dictionary<string, Run>();
foreach (Paragraph pap in _Outputdoc.Descendants<Paragraph>())
{
string tmpe = pap.InnerText;
if (tmpe == "") {
continue;
}
if (_dic.ContainsKey(tmpe) == false)
{
Text text = new Text(tmpe);
Run run = new Run();
run.Append(text);
Paragraph newParagraph = new Paragraph(run);
pap.InnerXml = newParagraph.InnerXml;
Run r = (Run)pap.FirstChild;
_dic.Add(tmpe, r);
}
else { pap.Remove(); }
}
_xmlString = _Outputdoc.InnerXml;
}
private void FontSetting(Run r, string Fonts, System.Drawing.Color color)
{
string ColorCode = string.Empty;
ColorCode = string.Format("{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
RunProperties runProp = new RunProperties();
runProp.Color = new Color() { Val = ColorCode };
runProp.RunFonts = new RunFonts { Ascii = Fonts, EastAsia = Fonts };
r.RunProperties = runProp;
_xmlString = _Outputdoc.InnerXml;
}
public void ReplaceText(string oldValue, string newValue, string Fonts, System.Drawing.Color color) {
if (_dic.Count == 0)
{
GetRunList();
}
foreach (Paragraph pap in _Outputdoc.Descendants<Paragraph>())
{
if (pap.InnerText.Trim() == oldValue.Trim()) {
FontSetting((Run)pap.FirstChild, Fonts, color);
break;
}
}
_xmlString = _xmlString.Replace(oldValue, newValue);
_Outputdoc.InnerXml = _xmlString;
}
public void Save()
{
_Outputdoc.Save();
}
public void SaveAs(string OutputFile) {
WordprocessingDocument package = WordprocessingDocument.Create(OutputFile, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
package.AddMainDocumentPart();
package.MainDocumentPart.Document = new Document(new Body());
package.MainDocumentPart.Document.InnerXml = _Outputdoc.InnerXml;
package.MainDocumentPart.Document.Save();
package.Close();
}
}
沒有留言:
張貼留言