C# 读取Word表格到DataSet

简介: C# 读取Word表格到DataSet

功能需求

在应用项目里,多数情况下我们会遇到导入 Excel 文件数据到数据库的功能需求,但某些情况下,也存在使用 Word 进行表格数据编辑的情况。Word 和 Excel 其实各有特点,用户的习惯不同,即使同一数据源,可能提供的数据源文件类型也不同,这其中也包括导入Word内容的功能,比如表格数据导出到DataSet数据集。

Office 数据源的一些映射关系

下图是一个简单的 Office 数据源的映射关系:

1、第一层级比如 WORD / EXCEL 为应用层级(Application)、 DATASET / DATABASE 为数据容器

2、第二层级,比如WORD 包含一个文档对象(Docment)、Excel 包含一个工作簿对象(WorkBook)、DataSet / DataBase 包括一组数据表对象(Tables)

3、第三层级,比如Word里的表格对象(Table)、Excel里的工作表对象(Sheet)

最实际的工作任务,是要将Table或Sheet对象的二维数据对应导出生成到 DataSet 里的 Table 对象,如果有多个则生成对应的集合。最后我们可能会再次导出到 DataBase 的数据表集合里(Tables)。

范例运行环境

操作系统: Windows Server 2019 DataCenter

操作系统上安装 Office Word 2016

.net版本: .netFramework4.7.1 或以上

开发工具:VS2019  C#

配置Office DCOM

对于安装原生Office应用,我们需要对DCOM进行进一步的配置方可使用其API。

打开控制面板、管理工具、组件服务:

点击组件服务、计算机、我的电脑、DCOM配置

找到 Microsoft Word97-2003 文档应用程序

选择属性、打开标识选项卡、选择下列用户选项,设置启动Word应用的用户,点确定即可。

理论上设置到这里就可以了,但以防万一,可以继续设置启动权限,选择安全选项卡、启动和激活权限,如下图:

关键代码

组件库引入

核心代码

public DataSet WordAsDataSet(string _filename) 方法,传入要读取的 WORD 文件路径即可,方法会遍历该WORD里的TABLES对象集合,如果找到TABLE对象,则按列的顺序创建字段列,比如F1、F2...Fn,以些类推,从第二行起为记录行,则根据创建的结构写入到 DataTable中。

        public DataSet WordAsDataSet(string _filename)
        {
            DataSet ds = new DataSet();
 
            Object Nothing = System.Reflection.Missing.Value;
 
            object filename = _filename;
            //创建一个名为WordApp的组件对象
            DateTime beforetime = DateTime.Now;
            Word.Application WordApp = new Word.Application();
            //创建一个名为WordDoc的文档对象
            WordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
 
            Word.Document WordDoc = WordApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
 
            WordDoc.SpellingChecked = false;//关闭拼写检查
 
            WordDoc.ShowSpellingErrors = false;//关闭显示拼写错误提示框
 
            DateTime aftertime = DateTime.Now;
//遍历所有的Word里的表格,并写到数据集的TABLES集合里
            foreach (Word.Table wTable in WordDoc.Tables)
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                for (int colPos = 1; colPos <= wTable.Columns.Count; colPos++)
                {
                    DataColumn dc = new DataColumn();
                    dc.ColumnName = "F" + colPos.ToString();
                    dt.Columns.Add(dc);
                }
 
                for (int rowPos = 1; rowPos <= wTable.Rows.Count; rowPos++)
                {
                    DataRow drNew = dt.NewRow();
                    int columnIndex = 0;
                    foreach (Word.Cell cellObj in wTable.Rows[rowPos].Cells)
                    {
                        drNew[columnIndex] = cellObj.Range.Text.Remove(cellObj.Range.Text.Length - 2, 2);//remove \r\a
                        columnIndex++;
                    }
                    dt.Rows.Add(drNew);
                }
                ds.Tables.Add(dt);
            }
 
 
            WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            //关闭WordApp组件对象
            WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
 
            KillProcessByStartTime("WINWORD", beforetime, aftertime);
 
            return ds;
        }

杀掉进程

这是一个无奈之举,尝试了一些方法,但某些情况下仍然无法释放掉 Word 应用进程,因此根据时间点范围写了一个强制杀掉进程的方法。

示例代码如下:

        public DataSet WordAsDataSet(string _filename)
        {
            DataSet ds = new DataSet();
 
            Object Nothing = System.Reflection.Missing.Value;
 
            object filename = _filename;
            //创建一个名为WordApp的组件对象
            DateTime beforetime = DateTime.Now;
            Word.Application WordApp = new Word.Application();
            //创建一个名为WordDoc的文档对象
            WordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
 
            Word.Document WordDoc = WordApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
 
            WordDoc.SpellingChecked = false;//关闭拼写检查
 
            WordDoc.ShowSpellingErrors = false;//关闭显示拼写错误提示框
 
            DateTime aftertime = DateTime.Now;
//遍历所有的Word里的表格,并写到数据集的TABLES集合里
            foreach (Word.Table wTable in WordDoc.Tables)
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                for (int colPos = 1; colPos <= wTable.Columns.Count; colPos++)
                {
                    DataColumn dc = new DataColumn();
                    dc.ColumnName = "F" + colPos.ToString();
                    dt.Columns.Add(dc);
                }
 
                for (int rowPos = 1; rowPos <= wTable.Rows.Count; rowPos++)
                {
                    DataRow drNew = dt.NewRow();
                    int columnIndex = 0;
                    foreach (Word.Cell cellObj in wTable.Rows[rowPos].Cells)
                    {
                        drNew[columnIndex] = cellObj.Range.Text.Remove(cellObj.Range.Text.Length - 2, 2);//remove \r\a
                        columnIndex++;
                    }
                    dt.Rows.Add(drNew);
                }
                ds.Tables.Add(dt);
            }
 
 
            WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            //关闭WordApp组件对象
            WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
 
            KillProcessByStartTime("WINWORD", beforetime, aftertime);
 
            return ds;
        }

总结

在实际的应用中,无论是导入的文件格式还是导出的数据源,都是要结合客户的需求进行的。

在功能实现前,需要约定模板文件的格式,字段内容的意义、长度等。导入到 DataSet 成功后,再根据业务逻辑进行后续操作再加工,或直接导入到规范的数据表里(如 MS SQL SERVER)。

这些代码我们提供了一些操作WORD相关的关键方法,这里仅作参考,欢迎大家评论指教!

相关文章
|
1月前
|
C# 开发工具 数据安全/隐私保护
C# 实现 Word 加盖骑缝章效果
C# 实现 Word 加盖骑缝章效果
|
1月前
|
存储 SQL 数据库
C# 将 Word 转文本存储到数据库并进行管理
C# 将 Word 转文本存储到数据库并进行管理
|
1月前
|
存储 SQL C#
C# 读取二维数组集合输出到Word预设表格
C# 读取二维数组集合输出到Word预设表格
|
1月前
|
SQL C# 数据库
C# 读取多条数据记录导出到 Word 标签模板
C# 读取多条数据记录导出到 Word 标签模板
|
1月前
|
C# 开发工具 数据安全/隐私保护
C#实现基于Word保护性模板文件的修改
C#实现基于Word保护性模板文件的修改
|
1月前
|
JavaScript API C#
C# 将 Word 转化分享为电子期刊
C# 将 Word 转化分享为电子期刊
|
4月前
|
存储 JSON 程序员
C#实现数据导出任一Word图表的通用呈现方法及一些体会
C#实现数据导出任一Word图表的通用呈现方法及一些体会
|
5月前
|
XML JSON 开发框架
盘点5个C#实用的Word、PPT、Excel、Mail第三方库
盘点5个C#实用的Word、PPT、Excel、Mail第三方库
85 0
|
1月前
|
C#
24. C# 编程:用户设定敌人初始血值的实现
24. C# 编程:用户设定敌人初始血值的实现
22 0
|
2月前
|
SQL 数据库连接 应用服务中间件
C#WinForm基础编程(三)
C#WinForm基础编程
79 0