前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spire.Doc组件读取与写入Word

Spire.Doc组件读取与写入Word

作者头像
用户1168362
发布2018-01-05 15:46:07
1.8K0
发布2018-01-05 15:46:07
举报
文章被收录于专栏:.net core新时代.net core新时代

  之前写了一篇开源组件DocX读写word的文章,当时时间比较匆忙选了这个组件,使用过程中还是有些不便,不能提前定义好模版,插入Form表单域进行替换。最近无意中发现Spire.Doc组件功能很强大,目前来看基本上符合我的所有使用场景。本篇将挑选几个重要的应用场景进行介绍。

阅读目录

  • 使用模版生成简历
  • 格式转换
  • Table操作
  • 总结

回到顶部

使用模版生成简历

  使用word的FormField预先插入占位符,然后在代码中获取所有FormField,进行替换。这种场景特别适用于,模版固定动态更改内容。看看最终效果

    表单域制作步骤

    1.打开word中的开发工具选项,对于导航栏中没有这一项的,可以通过 文件->选项->自定义功能区->开发工具 进行打开

   2.插入TextField, 属性->设置书签名称

  模版制作完成后,来看看实现代码

代码语言:javascript
复制
class Program
    {
        private static BindingFlags s_flag = BindingFlags.Instance | BindingFlags.Public;

        static void Main(string[] args)
        {
            Console.WriteLine("\nRunning Examples");

            Resume personResume = new Resume
            {

                Name = "Spire.Doc",//姓名
                Marriage = "未婚",//婚姻
                Birth = "2010-09-19",//出生年月
                Political = "团员",//政治面貌
                Sex = "男",//性别
                Nation = "汉族",//民族
                Degree = "大学本科",//学位
                Mobile = "13567890987",//移动电话
                Professional = "软件工程",//专业
                Email = "2345678@qq.com",//邮箱
                Adress = "故宫", //地址
                MajorCourse = "数据结构,C语言,算法,C++",//主修课程
                PersonalAbility = "熟练掌握DocX操作Word,SQL能力强悍",//个人能力
                ComputerAbility = "高级软件工程师",//计算机能力
                LanguageLevel = "CET-4,CET-6",//外语水平
                Awards = "1999年几月  曾获优秀班干部,3等奖学金1999年几月  曾获校优秀干部,学生会先进集体,2等奖学金20**年几月  曾获优秀学习委员,网络技术协会负责人,……………………",//奖励情况
                SelfEvaluation = "本人性格开朗、稳重、有活力,待人热情、真诚;工作认真负责,积极主动,能吃苦耐劳,用于承受压力,勇于创新;有很强的组织能力和团队协作精神,具有较强的适应能力;纪律性强,工作积极配合;意志坚强,具有较强的无私奉献精神"//自我评价
            };
            CreateResume(personResume);

            Console.WriteLine("\nPress any key to exit.");
            Console.ReadKey();
        }

        private static void CreateResume(Resume personResume)
        {
            Document doc = new Document(@"ResumeTemplate.docx");
            //清除表单域阴影
            doc.Properties.FormFieldShading=false;
            try
            {
                Type type = typeof(Resume);
                PropertyInfo[] properties = type.GetProperties(s_flag);
                int length = properties.Length;
                Dictionary<string, PropertyInfo> dict = new Dictionary<string, PropertyInfo>(length, StringComparer.OrdinalIgnoreCase);
                foreach (PropertyInfo prop in properties)
                {
                    dict[prop.Name] = prop;
                }
                object value = null;
                foreach (FormField field in doc.Sections[0].Body.FormFields)
                {            //field.name对应设置模版文本域名称
                    PropertyInfo prop = dict[field.Name];

                    if (prop != null)
                    {
                        value = prop.GetValue(personResume, null);
                        if (value != null && value != DBNull.Value)
                        {
                            switch (field.Type)
                            {
                                case FieldType.FieldFormTextInput:
                                    field.Text = value.ToString();
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                doc.SaveToFile(@"DocXResume.docx", FileFormat.Docx);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
代码语言:javascript
复制
  public class Resume
    {
        public string Name { get; set; }

        public string Marriage { get; set; }

        public string Birth { get; set; }

        public string Political { get; set; }

        public string Sex { get; set; }

        public string Nation { get; set; }

        public string Degree { get; set; }

        public string Mobile { get; set; }

        public string Professional { get; set; }

        public string Email { get; set; }

        public string Adress { get; set; }

        public string MajorCourse { get; set; }

        public string PersonalAbility { get; set; }

        public string ComputerAbility { get; set; }

        public string LanguageLevel { get; set; }

        public string Awards { get; set; }

        public string SelfEvaluation { get; set; }
    }

View Code

  重点关注上面标红的代码,可以看到通过简单的代码即可完成一份简历文档 

回到顶部

格式转换

  使用Spire.Doc可以很方便的将word转换成HTML,RTF,PDF,TXT,WPS...等格式

代码语言:javascript
复制
Document doc = new Document(@"SpireDocResume.docx"); //Save doc file.
doc.SaveToFile("SpireDocResume.html", FileFormat.Html);

    效果和直接打开word是一样的,有了这功能就能实现在线word预览,之前的一篇在线文档预览方案也可以参考一下。其它格式的转换也是一样的代码,改一下FileFormat枚举值即可。

回到顶部

Table操作

代码语言:javascript
复制
 private static void addTable(Section section)
        {
            String[] header = { "Name", "Capital", "Continent", "Area", "Population" };
            String[][] data =
                {
                    new String[]{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"},
                    new String[]{"Bolivia", "La Paz", "South America", "1098575", "7300000"},
                    new String[]{"Brazil", "Brasilia", "South America", "8511196", "150400000"},
                    new String[]{"Canada", "Ottawa", "North America", "9976147", "26500000"},
                    new String[]{"Chile", "Santiago", "South America", "756943", "13200000"},
                    new String[]{"Colombia", "Bagota", "South America", "1138907", "33000000"},
                    new String[]{"Cuba", "Havana", "North America", "114524", "10600000"},
                    new String[]{"Ecuador", "Quito", "South America", "455502", "10600000"},
                    new String[]{"El Salvador", "San Salvador", "North America", "20865", "5300000"},
                    new String[]{"Guyana", "Georgetown", "South America", "214969", "800000"},
                    new String[]{"Jamaica", "Kingston", "North America", "11424", "2500000"},
                    new String[]{"Mexico", "Mexico City", "North America", "1967180", "88600000"},
                    new String[]{"Nicaragua", "Managua", "North America", "139000", "3900000"},
                    new String[]{"Paraguay", "Asuncion", "South America", "406576", "4660000"},
                    new String[]{"Peru", "Lima", "South America", "1285215", "21600000"},
                    new String[]{"United States of America", "Washington", "North America", "9363130", "249200000"},
                    new String[]{"Uruguay", "Montevideo", "South America", "176140", "3002000"},
                    new String[]{"Venezuela", "Caracas", "South America", "912047", "19700000"}
                };
            Spire.Doc.Table table = section.AddTable();
            table.ResetCells(data.Length + 1, header.Length);

            // ***************** First Row *************************
            TableRow row = table.Rows[0];
            row.IsHeader = true;
            row.Height = 20;    //unit: point, 1point = 0.3528 mm
            row.HeightType = TableRowHeightType.Exactly;
            row.RowFormat.BackColor = Color.Gray;
            for (int i = 0; i < header.Length; i++)
            {
                row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                Paragraph p = row.Cells[i].AddParagraph();
                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                TextRange txtRange = p.AppendText(header[i]);
                txtRange.CharacterFormat.Bold = true;
            }

            for (int r = 0; r < data.Length; r++)
            {
                TableRow dataRow = table.Rows[r + 1];
                dataRow.Height = 20;
                dataRow.HeightType = TableRowHeightType.Exactly;
                dataRow.RowFormat.BackColor = Color.Empty;
                for (int c = 0; c < data[r].Length; c++)
                {
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    dataRow.Cells[c].AddParagraph().AppendText(data[r][c]);
                }
            }
        }

回到顶部

总结

   通过上面三个简单的例子,粗略的了解了Spire.Doc。下面就我个人对DocX和Spire.Doc使用,列出两种优缺点。

Spire.Doc

DocX

API

介绍简单

无API介绍

Demo

提供了很多Demo方便学习

demo少

收费

收费

开源免费

功能对比

1.支持FormField模版替换 2.Table读写功能强大

1.对自定义属性读写存在BUG

兼容性

兼容word各版本

支持2007即以上版本

依赖性

不依赖于office,即使服务器未装office也能正常操作

    实际开发中可以根据自己需要来选择使用Sprie.Doc或者DocX。

    本文例子Demo下载地址:SpireDoc_Demo

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-10-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用模版生成简历
  • 格式转换
  • Table操作
  • 总结
相关产品与服务
Prowork 团队协同
ProWork 团队协同(以下简称 ProWork )是便捷高效的协同平台,为团队中的不同角色提供支持。团队成员可以通过日历、清单来规划每⽇的工作,同时管理者也可以通过统计报表随时掌握团队状况。ProWork 摒弃了僵化的流程,通过灵活轻量的任务管理体系,满足不同团队的实际情况,目前 ProWork 所有功能均可免费使用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档