程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> ASP編程 >> ASP技巧 >> Syncfusion Essential DocIO操作word文件實用函數

Syncfusion Essential DocIO操作word文件實用函數

編輯:ASP技巧

Essential DocIO

.Net庫,能夠讀寫Microsoft Word文件。該組件是一個對象模型,同Microsoft Office COM類庫相似,它不采用COM interop,以C#編寫。如果系統內沒有安裝Microsoft Word,可以考慮該組件。

創建新的MS Word文檔:支持創建包含文本、圖片、圖表、頁面和頁腳的MS Word文檔。

文檔格式化:支持格式化為通用的MS Word 報告。

文檔生成基於模板:基於模板生成文檔,可以使用MS Word GUI設計文檔報告,然後使用DocIO向模板文件內動態填充數據。

文檔屬性:讀寫Word文檔的屬性設置。

轉換:支持使用Essential PDF將MS Word文檔轉換為PDF。

高級特性:支持復制和合並多個MS Word文檔為單個文檔。
轉換Html到Word
        public static byte[] ConvertHtmlToDoc(string Html)
        {
            var document = new WordDocument();
            IWSection section = document.AddSection();
            IWParagraph para = section.AddParagraph();
           
            string errorMessage = "";
            bool valid = section.Body.IsValidXHTML(html, XHtmlValidationType.Strict, out errorMessage);
            if (!valid)
                throw new InvalidCastException(errorMessage + "<hr>" + Html) ;
            document.XHTMLValidateOption = XHtmlValidationType.Strict;
            section.Body.InsertXHTML(Html);
            var outMem = new MemoryStream();

            document.Save(outMem, FormatType.Doc);
            outMem.Seek(0, SeekOrigin.Begin);
            var content = new byte[outMem.Length];
            outMem.Read(content, 0, content.Length);
            outMem.Dispose();
            document.Close();
            return content;
        }


生成Word的時候替換指定的文字
        /// <summary>
        /// 生成Word的時候替換指定的文字
        /// </summary>
        /// <param name="templatePath"></param>
        /// <param name="FileName"></param>
        /// <param name="replaysDictionary"></param>
        public static void ReplaceDocContent(string templateFileName, string newFileName,
                                             Dictionary<string, string> replaysDictionary)
        {
            IWordDocument document = new WordDocument();
            document.Open(templateFileName, FormatType.Doc);
            foreach (var rd in replaysDictionary)
            {
                if (string.IsNullOrEmpty(document.GetText())) continue;

                document.Replace(rd.Key, rd.Value, false, false);
                while (document.GetText().IndexOf(rd.Key) != -1)
                    document.Replace(rd.Key, rd.Value, false, false);
            }
            document.Save(newFileName, FormatType.Doc);
        }


給文檔加密碼保護
        public static Stream SetDocPRotect(byte[] docContent, string key)
        {
            var mem = new MemoryStream(docContent);
            mem.Seek(0, SeekOrigin.Begin);

            IWordDocument document = new WordDocument(mem, FormatType.Automatic);
            document.Protect(ProtectionType.AllowOnlyFormFIElds, key);
            var outMem = new MemoryStream();
            document.Save(outMem, FormatType.Doc);
            outMem.Seek(0, SeekOrigin.Begin);
            return outMem;
        }


在書簽位置創建一個表格
        public static IWTable ReplaceTable(WordDocument document, string bookmarkName, DataTable data, string mergeColName , List<List<string>> mutilTableCaption)
        {
            if (document == null) throw new ArgumentNullException("document");
            if (bookmarkName == null) throw new ArgumentNullException("bookmarkName");
            if (data == null) throw new ArgumentNullException("data");
            if (data.Columns.Count < 1) throw new ArgumentNullException("data");
           
            int captionCount = mutilTableCaption != null && mutilTableCaption.Count > 0 ? mutilTableCaption.Count : 1;
            WTable table = new WTable(document, true);

            table.ResetCells(data.Rows.Count + captionCount, data.Columns.Count);

            for (var colCount = 0; colCount < captionCount; colCount++)
            {
                for (var col = 0; col < data.Columns.Count; col++)
                {
                    var paragraph = table.Rows[colCount].Cells[col].AddParagraph();

                    var caption = data.Columns[col].ColumnName;
                    if (mutilTableCaption != null && mutilTableCaption.Count > 0)
                        caption = mutilTableCaption[colCount][col];
                    var text = paragraph.AppendText(caption);
                    paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
                    text.CharacterFormat.FontName = "宋體";
                    text.CharacterFormat.Bold = false;
                    text.CharacterFormat.FontSize = 10.5f;
                }
            }

            for (var row = captionCount; row <= data.Rows.Count; row++)
                for (var col = 0; col < data.Columns.Count; col++)
                {
                    var paragraph = table.Rows[row].Cells[col].AddParagraph();
                    var text = paragraph.AppendText(data.Rows[row - captionCount][col] + "");

                    text.CharacterFormat.FontName = "宋體";
                    text.CharacterFormat.FontSize = 9f;
                    double val = 0;
                    if (double.TryParse(text.Text, out val))
                    {
                        text.Text = Math.Round(val, 2) + "";
                        //align right
                        paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
                        table.Rows[row].Cells[col].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        table.Rows[row].Cells[col].CellFormat.TextWrap = false;
                    }
                }
            //合並單元格,向下合並
            if (!string.IsNullOrEmpty(mergeColName))
                for (var row = captionCount; row < table.Rows.Count; row++)
                {
                    var cell = table.Rows[row].Cells[data.Columns[mergeColName].Ordinal];
                    cell.CellFormat.VerticalMerge = CellMerge.Start;
                    var text = data.Rows[row - captionCount][mergeColName] + "";
                    if (row > captionCount)
                    {
                        var priorCell = table.Rows[row - captionCount].Cells[data.Columns[mergeColName].Ordinal];
                        var findText = data.Rows[row - captionCount - 1][mergeColName] + "";
                        if (text.Equals(findText))
                            cell.CellFormat.VerticalMerge = CellMerge.Continue;
                    }
                }

            BookmarksNavigator bk = new BookmarksNavigator(document);
            bk.MoveToBookmark(bookmarkName);

            TextBodyPart body= bk.GetBookmarkContent();
            bk.DeleteBookmarkContent(true);

            bk.InsertTable(table);
            return table;
        }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved