C#導出數據—使用Word模板

前言

本文主要介紹C#使用標籤替換的方法導出數據,導出的數據模板使用Word文檔。

模板建立

首先創建一個Word文檔,然後建立一個基礎模板。然後將上方菜單切換到插入菜單。

然後在想填充數據的地方添加書籤,如下圖,游標在年的前方,點擊上方的書籤按鈕。

書籤全部添加完如下圖所示:

書籤默認是看不到的,我們可以打開文件下的選項頁面,然後在視圖裡勾選書籤選項,讓書籤顯示出來,如下圖:

勾選後,書籤位置會有一個豎線顯示,結果如下圖所示:

程式碼實現

新建一個項目WordExport。

然後Nuget添加引用Microsoft.Office.Interop.Word。

然後在頁面里添加一個按鈕,然後在點擊事件里實現如下程式碼:

private void Button_Click(object sender, RoutedEventArgs e)
{
    try
    { 
        string wordTemplatePath = System.Windows.Forms.Application.StartupPath + @"\Word模板.docx";
        if (File.Exists(wordTemplatePath))
        {
            System.Windows.Forms.FolderBrowserDialog dirDialog = new System.Windows.Forms.FolderBrowserDialog();
            dirDialog.ShowDialog();
            if (dirDialog.SelectedPath != string.Empty)
            {
                string newFileName = dirDialog.SelectedPath + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx";
                
                Dictionary<string, string> wordLableList = new Dictionary<string, string>();
                wordLableList.Add("年", "2021");
                wordLableList.Add("月", "9");
                wordLableList.Add("日", "18");
                wordLableList.Add("星期", "六");
                wordLableList.Add("標題", "Word導出數據");
                wordLableList.Add("內容", "我是內容——Kiba518");
​
                Export(wordTemplatePath, newFileName, wordLableList);
                MessageBox.Show("導出成功!");
            }
            else
            {
                MessageBox.Show("請選擇導出位置");
            } 
        }
        else
        { 
            MessageBox.Show("Word模板文件不存在!"); 
        } 
    }
    catch (Exception Ex)
    {
        MessageBox.Show(Ex.ToString());
        return;
    }
}
public static void Export(string wordTemplatePath, string newFileName, Dictionary<string, string> wordLableList)
{  
    Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
    string TemplateFile = wordTemplatePath;
    File.Copy(TemplateFile, newFileName);
    _Document doc = new Document();
    object obj_NewFileName = newFileName;
    object obj_Visible = false;
    object obj_ReadOnly = false;
    object obj_missing = System.Reflection.Missing.Value;
   
    doc = app.Documents.Open(ref obj_NewFileName, ref obj_missing, ref obj_ReadOnly, ref obj_missing,
        ref obj_missing, ref obj_missing, ref obj_missing, ref obj_missing,
        ref obj_missing, ref obj_missing, ref obj_missing, ref obj_Visible,
        ref obj_missing, ref obj_missing, ref obj_missing,
        ref obj_missing);
    doc.Activate();
​
    if (wordLableList.Count > 0)
    {
        object what = WdGoToItem.wdGoToBookmark; 
        foreach (var item in wordLableList)
        {
            object lableName = item.Key;
            if (doc.Bookmarks.Exists(item.Key))
            {
                doc.ActiveWindow.Selection.GoTo(ref what, ref obj_missing, ref obj_missing, ref lableName);//游標移動書籤的位置
                doc.ActiveWindow.Selection.TypeText(item.Value);//在書籤處插入的內容 
                doc.ActiveWindow.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//設置插入內容的Alignment
            }  
        }
    }
​
    object obj_IsSave = true;
    doc.Close(ref obj_IsSave, ref obj_missing, ref obj_missing);
​
}

程式碼里我們模擬了一個標籤要替換的內容字典,然後調用Microsoft.Office.Interop.Word命名空間下的類,實現對Word模板的書籤的替換。

運行項目,如下圖:

點擊導出按鈕,導出Word文檔如下:

 

—————————————————————————————————-

到此,C#導出數據—使用Word模板就已經介紹完了。

程式碼已經傳到Github上了,歡迎大家下載。

Github地址: //github.com/kiba518/WordExport

—————————————————————————————————-

註:此文章為原創,任何形式的轉載都請聯繫作者獲得授權並註明出處!
若您覺得這篇文章還不錯,請點擊下方的推薦】,非常感謝!

//www.cnblogs.com/kiba/p/15309344.html

 

 

Tags: