C#读取EXL中的数据步骤案例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;

namespace Excel操作
{
class Program
{
static void Main(string[] args)
{
//excel文件路径
string fileName = @"d:\文档\visual studio 2017\Projects\MyTest\Excel操作\装备信息.xls";
//连接字符串
//,xls后缀时用以下连接字符串
// "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//.xlsx后缀时用以下连接字符串
// "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//连接oledb
OleDbConnection connetction = new OleDbConnection(connectionString);
connetction.Open();
//查询语句
string sql = "select * from [Sheet1$]";
//将查询结果放入adapter数据适配器中
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connetction);
//建立一个空的Dataset数据集
DataSet dataSet = new DataSet();
//将adapter中的数据Fill到dataSet中
adapter.Fill(dataSet);
//关闭连接,此时查询结果数据已经在dataset中了
connetction.Close();
//取得dataSet中的tables集合
DataTableCollection tableCollection = dataSet.Tables;
//取得第一张table
DataTable table = tableCollection[0];
//取得table中的所有row
DataRowCollection rowCollection = table.Rows;
//遍列所有row中的信息(不括标题字段)
foreach (DataRow row in rowCollection)
{
for (int i = 0; i < 8; i++)
{
Console.Write(row[i] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}

转载于:https://www.cnblogs.com/trlq/p/7207802.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值