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;
                    }
                }
            }
        }
 
         

 




 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM