C# Aspose.Words将word中自定义的标签进行替换
需要将word中自定义的标签进行文本替换,并生成一个word报告文档
1.定义word模板文件如下
2.将模板文件添加到资源
3.生成word文件、替换标签
//取出Resources中的模板文件 string sourcePath = @"D:\temp.doc"; byte[] sampleXls = Properties.Resources.GroundSteelPipeCal_模板; FileStream outputExcelFile = new FileStream(sourcePath, FileMode.Create, FileAccess.Write); outputExcelFile.Write(sampleXls, 0, sampleXls.Length); outputExcelFile.Close(); outputExcelFile.Dispose(); //替换文本 Document doc = new Document(sourcePath); DocumentBuilder builder = new DocumentBuilder(doc); doc.Range.Replace("{标签}", "标签替换的值", false, false); doc.Save(sourcePath); //保存word //文件保存 SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Word Document(*.doc)|*.doc"; sfd.DefaultExt = "Word Document(*.doc)|*.doc"; if (sfd.ShowDialog() == DialogResult.OK) { try { string targetPath = sfd.FileName; File.Copy(sourcePath, targetPath, true); MessageBox.Show("报告文档生成成功"); } catch (Exception ex) { MessageBox.Show("报告文档生成失败,原因:" + ex.Message); } }