入门请看:
【原创翻译】开源Word读写组件DocX介绍与入门[资料已发送]我也是通过看上面的入门的。 1.DocX通过word模板批量导出用户简历由于Docx有两种方法可以自定义属性:1.1通过word模板文件(在word模板中定义好自定义属性) 1.2 用代码创建word模板,并同时用代码创建自定义属性。 1.1通过word模板文件(在word模板中定义好自定义属性),自己新建一个模板文件。
每个要替换的部分,都定义成自定义属性
域代码如下:TAge 就为自定义属性名称
代码如下: private void CreateInvoice() { DocX g_document; try { 下面代码为填充数据方法 private DocX CreateInvoiceFromTemplate(DocX template,DataRow dr) { //为自定义属性赋值,CustomerProperty(name,values),name就是我们刚刚在word中定义的名称。values就是要填充进去的内容 #region Set CustomProperty values template.AddCustomProperty(new CustomProperty("Translatorno", dr["translator_no"].ToString())); template.AddCustomProperty(new CustomProperty("TName", dr["name"].ToString())); template.AddCustomProperty(new CustomProperty("TAge", dr["age"].ToString())); template.AddCustomProperty(new CustomProperty("TSex", dr["sex"].ToString())); template.AddCustomProperty(new CustomProperty("TNationality", dr["nationality"].ToString())); #endregion return template; } 1.2 用代码创建word模板,并同时用代码为word模板创建自定义属性。 private static DocX CreateInvoiceTemplate() { // 创建一个文档 DocX document = DocX.Create(@"docs\InvoiceTemplate.docx"); //先创建了一个表格 Table layout_table = document.InsertTable(2, 2); layout_table.Design = TableDesign.TableNormal; layout_table.AutoFit = AutoFit.Window; // 定义格式 Formatting dark_formatting = new Formatting(); dark_formatting.Bold = true; dark_formatting.Size = 12; dark_formatting.FontColor = Color.FromArgb(31, 73, 125); // 定义格式 Formatting light_formatting = new Formatting(); light_formatting.Italic = true; light_formatting.Size = 11; light_formatting.FontColor = Color.FromArgb(79, 129, 189); #region Company Name //取表格的第一行第一列的第一段落 Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0]; // 新建一个自定义属性。其对应word中的内容是Translatorno为自定义属性名称,translatorno,为我们自己的word里面的内容 CustomProperty company_name = new CustomProperty("Translatorno", "translatorno"); // 加入自定义属性 layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f: dark_formatting); 2.资源开源网址:http://docx./ 写篇博客不容易,烦躁的心情都见鬼去吧。兄弟们,对你有帮助,不要吝啬鼠标哦。 可以去下载示例代码。 |
|
来自: 贾朋亮博客 > 《Word,Excel》