需求:天天向全国各运营大区钉钉运营群定时发送pdf业务运营报告;html
经过对各Office操做组件对比,选择Spire.Doc。它专门为开发人员进行建立,读取,写入、转换打印 word 文档文件提供便利,不须要安装 MS Office便可对 word、Excel、Pdf 进行操做。包含商业版与免费版,其中免费版对文档页数有限制(Free version is limited to 500 paragraphs and 25 tables. This limitation is enforced during reading or writing files. When converting word documents to PDF and XPS files, you can only get the first 3 page of PDF file.)。官方地址:https://www.e-iceblue.com/工具
组件安装字体
经常使用操做this
一、加载Word模板spa
Document document = new Document(); document.LoadFromFile("sample.docx", FileFormat.Docx);
2 、获取模板中的表格code
//获取第一个节
Section section = document.Sections[0]; //获取第一个表格,若模板中有多个表格,则序号从0开始依次顺延
Table table = section.Tables[0] as Table;
三、表格行列操做orm
//添加一行到表格的最后
table.AddRow(true, 4); //插入一行到表格的第三行
table.Rows.Insert(2, table.AddRow()); //添加一列到表格,设置单元格的宽度和宽度类型
for (int i = 0; i < table.Rows.Count; i++) { TableCell cell = table.Rows[i].AddCell(true); cell.Width = table[0, 0].Width; cell.CellWidthType = table[0, 0].CellWidthType; } //删除第二行
table.Rows.RemoveAt(1); //删除第二列
for (int i = 0; i < table.Rows.Count; i++) { table.Rows[i].Cells.RemoveAt(1); } //设置第一行的行高
table.Rows[0].Height = 40; //设置第二列的列宽
for (int i = 0; i < table.Rows.Count; i++) { table.Rows[i].Cells[1].Width = 40; }
四、表格单元格赋值及样式 htm
//添加第1行
TableRow row1 = table.AddRow(); //添加第1个单元格到第1行
TableCell cell1 = row1.AddCell(); cell1.AddParagraph().AppendText("姓 名"); //添加第2个单元格到第1行
TableCell cell2 = row1.AddCell(); cell2.AddParagraph().AppendText("年 龄"); //设置表格的第二行第一列水平居左
table[1, 0].Paragraphs[0].Format.HorizontalAlignment = HorizontalAlignment.Left; //设置表格第二行第一列垂直居上
table[1,0].CellFormat.VerticalAlignment = VerticalAlignment.Top; //设置第二行第一个单元格的背景颜色
table[1,0].CellFormat.BackColor = Color.SeaGreen; //经过 TextRange.CharacterFormat 来设置单元格内文本属性,如:阴影,字体、颜色等
TextRange HText = paragraph.AppendText("this is a test!"); HText.CharacterFormat.IsShadow = true; HText.CharacterFormat.FontSize = 80;
五、表格样式blog
/获取第一个表格 Table table = section.Tables[0] as Table; //给表格应用内置样式
table.ApplyStyle(DefaultTableStyle.LightGridAccent3); //设置表格的上边框
table.TableFormat.Borders.Top.BorderType = BorderStyle.Double; table.TableFormat.Borders.Top.LineWidth = 1.0F; table.TableFormat.Borders.Top.Color = Color.YellowGreen; //设置第一行的背景颜色
table.Rows[0].RowFormat.BackColor = Color.SeaGreen; //设置第一行第一个单元格的背景颜色
table[0,0].CellFormat.BackColor = Color.SeaGreen;
当word模板中的表格由Excel画好后,粘贴至Word,而后再读取模板中的表格时,上面的这些样式设置好象未起做用,待验证图片
六、写操做
//文档转换
ocument document = new Document(); document.LoadFromFile("sample.doc"); document.SaveToFile("result.html", FileFormat.Html); document.Close(); ocument.LoadFromFile("sample.html", FileFormat.Html, XHTMLValidationType.None); document.SaveToFile("result.doc"); document.Close(); //其它文件的转换相似
总结:对于Table表格的操做与DataTable操做很相似,在每一个单元格内 AddParagraph() 支持增长不一样的Range类型,如:文本、超链、表格嵌套等,这块的处理又与DevExpress控件的表格操做很相似,很赞,要是开源就更棒!
应用开发步骤
参考文档