基于C#的Excel数据导入导出研究与实现

2014-04-29 13:29:02蔡小艳
智能计算机与应用 2014年5期

蔡小艳

摘 要:为了提高信息管理系统中数据导入导出操作的灵活性和通用性,本文详细介绍了在Visual Studio 2008使用C#语言、通过引用Office的COM组件技术,结合Microsoft SQL Server 2005实现了Excel数据导入到数据库以及数据库数据导出到Excel的设计思路和实现方法。实践证明该方法有较强的通用性和实用性。

关键词:C#;COM组件;Excel;导入导出

中图分类号:TP311 文献标识码:A 文章编号:2095-2163(2014)05-

Research and Implementation of Excel Data Import and Export Based on C#

CAI Xiaoyan, LI Longteng, GE Yu, ZHENG Yan

(Wuhan ordnance officer school,Wuhan 430075,China)

Abstract: In order to improve the flexibility and popularity of data import and export in information management system, this paper introduces the ideas and the ways of implementation of Excel data importing to database and database data exporting to Excel, which combined with Microsoft SQL Server 2005 in Visual Studio 2008, uses C# programme, and applies COM components technology of Office. The operation practices show that the method if widely useful and available.

Key words: C#; COM components; Excel; import and export

0 引 言

Excel是Office的重要组成,是保存统计数据的常用软件格式之一。在程序编制和数据汇总交换过程中,能否将系统中录入的数据以及查询的结果按标准的格式导出为Excel报表,以及能否将Excel表中的数据进行整理后批量导入数据库,以上过程均对系统设计提出了较高要求。基于此,本文即介绍了在.Net环境下,使用C#语言实现系统中Excel数据与SQL Server2005数据库中数据的导入导出。

1 设计思路

1.1数据导入设计思路

在此,将Excel表格中的数据导入到SQL Server数据库的设计思路进行如下表述:

(1)由c#程序控制Excel表格,首先打开Excel表格;

(2)运用SQL语句,执行SQL,并根据不同的规则,将表格中的数据读入到临时表temp_table中;

(3)通过对比temp_table和table,判断是否存在重复的数据,提示是否重复导入;

(4)如果重复导入,可将temp_table的数据直接添加到table中;否则即需将temp_table中除关键字冲突外的其它数据添加到table中。

1.2数据导出设计思路

相应地,SQL Server数据库中的数据导出到Excel表格的设计思路[1-3]可列述如下:

(1)选择需要导出的数据;

(2)利用Worksheet类创建Excel工作表对象,确定即将写入数据的单元格位置;

(3)从数据库中读取数据,根据数据类型的不同,选择不同的写入方式;……

登录APP查看全文