zoukankan      html  css  js  c++  java
  • C#导出数据—使用Word模板书签的使用

    前言

    本文主要介绍C#使用标签替换的方法导出数据,导出的数据模板使用Word文档。

    模板建立

    首先创建一个Word文档,然后建立一个基础模板。然后将上方菜单切换到插入菜单。

    然后在想填充数据的地方添加书签,如下图,光标在年的前方,点击上方的书签按钮。

    书签全部添加完如下图所示:

    书签默认是看不到的,我们可以打开文件下的选项页面,然后在视图里勾选书签选项,让书签显示出来,如下图:

    勾选后,书签位置会有一个竖线显示,结果如下图所示:

    代码实现

    新建一个项目WordExport。

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

    然后在页面里添加一个按钮,然后在点击事件里实现如下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    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地址: https://github.com/kiba518/WordExport

    ----------------------------------------------------------------------------------------------------

    注:此文章为原创,任何形式的转载都请联系作者获得授权并注明出处!
    若您觉得这篇文章还不错,请点击下方的推荐】,非常感谢!

    出处:https://www.cnblogs.com/kiba/p/15309344.html

    您的资助是我最大的动力!
    金额随意,欢迎来赏!
    款后有任何问题请给我留言。

    如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
    如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我。(●'◡'●)

    如果你觉得本篇文章对你有所帮助,请给予我更多的鼓励,求打             付款后有任何问题请给我留言!!!

    因为,我的写作热情也离不开您的肯定支持,感谢您的阅读,我是【Jack_孟】!

  • 相关阅读:
    PHP调用WCF提供的方法
    关于git报 warning: LF will be replaced by CRLF in README.md.的警告的解决办法
    vue中引入mui报Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them的错误
    微信小程序报Cannot read property 'setData' of undefined的错误
    Vue那些事儿之用visual stuido code编写vue报的错误Elements in iteration expect to have 'v-bind:key' directives.
    关于xampp中无法启动mysql,Attempting to start MySQL service...的解决办法!!
    PHP的环境搭建
    新手PHP连接MySQL数据库出问题(Warning: mysqli_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES))
    手机号码、获得当前时间,下拉框,填写限制
    团队作业(五):冲刺总结
  • 原文地址:https://www.cnblogs.com/mq0036/p/15319660.html
Copyright © 2011-2022 走看看