OLEDB需要从NGGET引入
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Text;
using System.Data.OleDb;
using System.Data;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
//oledb缺陷在于无法单独读取一格的内容,必须读取整张表,因而适合整体的数据转移
//"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\""; 适用于xls
//"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; 适用于xlsx
string fileName = "test.xls";
string connectionString= "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
string sql = "select * from [Sheet1$]";//一条sql语句
OleDbDataAdapter asapter = new OleDbDataAdapter(sql,connection);
DataSet dataset = new DataSet();
asapter.Fill(dataset);//将适配器asapter中的内容填充到dataset中
DataTableCollection dataTableCollection = dataset.Tables;//取出其中的所有表
DataTable dataTable = dataTableCollection[0];//将第一张表存为datatable
DataRowCollection dataRow = dataTable.Rows;//返回一个行的集合
foreach(DataRow temp in dataRow)
{
for(int i=0;temp[i]!="";i++)
{
Console.Write(temp[i] + " ");
}
Console.WriteLine();
}
}
}
}