C#中数据库数据如何导出至Excel表格
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#中数据库数据如何导出至Excel表格
有时候需要将数据库的数据导出至Excel表格表格,以便进行查看和分析,那么如何导出呢?下面用代码来实现。
首先,新建一个工程,需要添加引用Microsoft.Office.Interop.Excel.dll,以Oracle数据
库为例(只要读出DataTable或DataSet就行了,哪种数据库没关系)。
1、创建一个表格,并插入如下数据。
[sql]view plaincopyprint?
1.drop table TABLETESTEXCEL;
2.create table TABLETESTEXCEL
3.(
4. col_id NUMBER not null,
5. col_name VARCHAR2(32),
6. col_age NUMBER,
7. col_sex VARCHAR2(4),
8. col_work VARCHAR2(32),
9. col_mony FLOAT
10.);
数据:
[sql]view plaincopyprint?
1.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
2.values (1, '吴一', 25, '男', '.NET', 5000);
3.
4.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
5.values (2, '孙二', 24, '男', 'JAVA', 4999);
6.
7.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
8.values (3, '张三', 25, '男', 'PHP', 5001);
9.
10.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
11.values (4, '李四', 26, '男', 'DELPHI', 5002);
12.
13.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
14.values (5, '王五', 27, '男', 'C++', 5003);
15.
16.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
17.values (6, '赵六', 25, '男', 'C', 4008);
18.
19.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
20.values (7, '燕七', 25, '男', '数据库', 4007);
21.
22.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
23.values (8, '胡八', 25, '男', 'JSP', 5005);
24.
25.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
26.values (9, '钱九', 25, '男', '', 4005);
27.
28.insert into TABLETESTEXCEL (col_id, col_name, col_age, col_sex, col_work,
col_mony)
29.values (10, '沈十', 25, '男', 'VB', 4000);
mit;
2、C#代码实现
数据库操作的类:
[csharp]view plaincopyprint?
1.public class DataBaseHelper
2. {
3. public static DataTable ExecuterQuery(string connectionString, string
commandSql)
4. {
5. DataTable dataTable = new DataTable();
6.
7. try
8. {
9. using (OracleConnection oracleConnection =
10. new OracleConnection(connectionString))
11. {
12. oracleConnection.Open();
13.
14. using (OracleDataAdapter oracleDataAdapter =
15. new OracleDataAdapter(commandSql,oracleConnection))
16. {
17. oracleDataAdapter.Fill(dataTable);
18. }
19.
20. oracleConnection.Close();
21. }
22. }
23. catch
24. {
25. return null;
26. }
27.
28. return dataTable;
29. }
30. }
[sql]view plaincopyprint?
1.public class DataBaseDao
2.{