C# OLEDB读取EXCEL

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();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值