需求:天天向全國各運營大區釘釘運營羣定時發送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控件的表格操做很相似,很贊,要是開源就更棒!
應用開發步驟
參考文檔