1建立测试excel
假定它第一排是标头,且含有价格/名称/编号字段
假定工作表名为sheet1
内容如下:
名称价格编号
A1221
B2.412
C583
2使用ado.net连接并读取excel
using System;
using System.Collections.Generic;
using System.Data.OleDb;
public class MyClass
{
public static void Main()
{
try{
OleDbConnection conn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d://readxls.xls;Extended Properties=/"Excel 8.0;HDR=YES;/"");
OleDbCommand comm=new OleDbCommand();
comm.Connection=conn;
conn.Open();
comm.CommandText="select * from [sheet1$]";
OleDbDataReader oddr=comm.ExecuteReader();
while(oddr.Read()){
Console.WriteLine("名称:{0}/t编号:{1}/t价格:{2}",oddr["名称"],oddr["编号"],oddr["价格"]);
}
conn.Close();
}
catch(Exception e){
Console.WriteLine(e.ToString());
}
finally{
Console.WriteLine("end of test");
Console.Read();
}
}
}
运行结果:
名称:A 编号:1 价格:122
名称:B 编号:12 价格:2.4
名称:C 编号:3 价格:58
end of test
本文介绍如何使用ADO.NET连接并读取Excel文件中的数据。示例代码展示了创建连接字符串、执行SQL查询以及读取结果集的具体步骤。
809

被折叠的 条评论
为什么被折叠?



