读取一个EXCEL文件用的类:
1/**//*
2 * 操作Excel文件类
3 * 目前功能列表:
4 * 1、读取Excel文件,返回一个DataSet
5 * 2、读取Excel文件,返回其工作表ArrayList
6 * by Lee 2008/11/27 11:51:56
7 * Copyright © 7thSpace
8 *
9 */
10
11using System;
12using System.Data;
13using System.Data.OleDb;
14using System.Collections;
15
16namespace LEE.OperateExcelFile
17{
18 public class OperateExcel
19 {
20 /**//// <summary>
21 /// 读取Excel文档中的Sheet1工作表
22 /// </summary>
23 /// <param name="path">文件路径</param>
24 /// <returns>返回DataSet数据集</returns>
25 public DataSet GetExcelToDataSet(string path)
26 {
27 string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
28 new OleDbConnection(connectionString).Open();
29 string selectCommandText = "";
30 OleDbDataAdapter adapter = null;
31 DataSet dataSet = null;
32 selectCommandText = "select * from [sheet1$]";
33 adapter = new OleDbDataAdapter(selectCommandText, connectionString);
34 dataSet = new DataSet();
35 adapter.Fill(dataSet, "table1");
36 return dataSet;
37 }
38
39 /**//// <summary>
40 /// 读取Excel文档中指定的工作表
41 /// </summary>
42 /// <param name="path">文件路径</param>
43 /// <param name="tablename">工作表名</param>
44 /// <returns>返回DataSet数据集</returns>
45 public DataSet GetExcelToDataSet(string path, string tablename)
46 {
47 string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
48 new OleDbConnection(connectionString).Open();
49 OleDbDataAdapter adapter = null;
50 DataSet dataSet = null;
51 adapter = new OleDbDataAdapter("select * from [" + tablename + "]", connectionString);
52 dataSet = new DataSet();
53 adapter.Fill(dataSet, tablename);
54 return dataSet;
55 }
56
57 /**//// <summary>
58 /// 获取Excel文档中的所有工作表清单
59 /// </summary>
60 /// <param name="path">文件路径</param>
61 /// <returns>返回ArrayList</returns>
62 public ArrayList GetExcelSheet(string path)
63 {
64 ArrayList tableName = new ArrayList();
65 using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + path))
66 {
67 conn.Open();
68 DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
69 for(int i=0; i<dt.Rows.Count; i++)
70 {
71 tableName.Add(dt.Rows[i][2].ToString());
72 }
73 }
74 return tableName;
75 }
76 }
77}
为了保证数据文件的安全性,.NET不提供以编程方式访问有密码的office文件。
可以搜一下破解密码的代码
在连接字符串里面写入密码就行了
例如连接yourExcel.xls,密码123456
string ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/yourExcel.xls;Extended Properties=Excel 8.0;Jet OLEDB:Database Password=123456;Persist Security Info=False";
你试一下看可不可以。