码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-07-19 22:04:51      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:foreach   lin   main   查询语句   key   system   语句   hdr   oid   

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();
}
}
}

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

标签:foreach   lin   main   查询语句   key   system   语句   hdr   oid   

原文地址:http://www.cnblogs.com/trlq/p/7207802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!