1. 程式人生 > >OpenXml操作word模板並匯出

OpenXml操作word模板並匯出

  在工作中,由於會需要對word模板進行資料填充,並匯出為新檔案,便對word相關的類庫做了簡單的瞭解。

  1.NPOI

          NPOI對excel的支援相當給力,但是對於word的支援卻明顯不到位,我在使用時匯出新檔案始終報錯無法開啟。

  2.Spire 

    功能強大,專業,支援全面。商業化軟體,需要收費,有免費版不過有限制(會在文件里加上版權文字,可以刪掉。。。)

  3.OpenXml

    較為底層的操作OpenXml文件的類庫,提供了對word的支援,功能全面,速度快。

    對word文件的操作,在我的需求裡 主要是填充word表格的資料 和替換段落的標籤資料。下面附程式碼

    需要使用到DocumentFormat.OpenXml類庫,nuget:install-package DocumentFormat.OpemXml 

 /// <summary>
        /// 設定表格資料
        /// </summary>
        /// <param name="tableIndex">表格索引</param>
        /// <param name="datatable">
資料表</param> /// <param name="configs">資料配置</param> /// <param name="headSpan">表頭佔用行數</param> public void SetTableData(int tableIndex, DataTable datatable, IList<WordTableColumnConfig> configs, int headSpan = 1) { if (doc == null)
throw new Exception("word parse failed."); if (tableIndex < 0 || tableIndex > Tables.Count - 1) throw new Exception("tableIndex is out of range."); if (datatable == null) throw new Exception("datatable can not be null."); if (configs == null || configs.Count == 0) throw new Exception("configs can not be null or less than 0."); if (datatable.Rows.Count == 0) return; for (int i = 0; i < datatable.Rows.Count; i++) { int rowIndex = i + headSpan; SetTableData(tableIndex, rowIndex, datatable.Rows[i], configs); } } /// <summary> /// 設定表格資料 /// </summary> /// <param name="tableIndex">表格索引</param> /// <param name="rowIndex">資料表格的行索引</param> /// <param name="dataRow">資料行</param> /// <param name="configs">資料列配置</param> public void SetTableData(int tableIndex, int rowIndex, DataRow dataRow, IList<WordTableColumnConfig> configs) { if (doc == null) throw new Exception("word parse failed."); if (tableIndex < 0 || tableIndex > Tables.Count - 1) throw new Exception("tableIndex is out of range."); if (dataRow == null) throw new Exception("dataRow can not be null."); if (configs == null || configs.Count == 0) throw new Exception("configs can not be null or less than 0."); if (rowIndex < 0) throw new Exception("rowIndex can not be less than 0."); if (rowIndex > Tables[tableIndex].ChildElements.Count - 2) return; rowIndex += 2; foreach (var config in configs) { if (!dataRow.Table.Columns.Contains(config.ColumnName)) continue; string value = dataRow[config.ColumnName] == null ? string.Empty : dataRow[config.ColumnName].ToString(); DocumentFormat.OpenXml.Wordprocessing.TableCell cell = (DocumentFormat.OpenXml.Wordprocessing.TableCell)Tables[tableIndex].ChildElements[rowIndex].ChildElements[config.WordColumnIndex + 1]; DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); p.PrependChild<DocumentFormat.OpenXml.Wordprocessing.Run>(new DocumentFormat.OpenXml.Wordprocessing.Run()); var run = p.Elements<DocumentFormat.OpenXml.Wordprocessing.Run>().First(); run.PrependChild<DocumentFormat.OpenXml.Wordprocessing.Text>(new DocumentFormat.OpenXml.Wordprocessing.Text() { Text = value }); cell.AppendChild<DocumentFormat.OpenXml.Wordprocessing.Paragraph>(p); } }

/// <summary>
        /// 設定標籤資料
        /// </summary>
        /// <param name="lableData">標籤資料</param>
        public void SetLableData(Dictionary<string, string> lableData)
        {
            if (doc == null)
                throw new Exception("word parse failed.");
            if (lableData == null)
                throw new Exception("lableData can not be null.");
            if (Paragraphs.Count == 0)
                return;
            var items = lableData.GetEnumerator();
            while (items.MoveNext())
            {
                var item = items.Current;
                foreach (var paragraph in Paragraphs)
                {
                    if (!paragraph.InnerText.Contains(item.Key))
                        continue;
                    var run = paragraph.Elements<DocumentFormat.OpenXml.Wordprocessing.Run>().FirstOrDefault(g => g.InnerText.Trim() == item.Key);
                    var text = run?.Elements<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault(g => g.Text.Trim() == item.Key);
                    if (text != null)
                    {
                        text.Text = item.Value;
                    }
                }
            }
        }
 
 

 




 

  第一次發博文,如果有問題,歡迎指出,歡迎交流。