C#中读取EXCEL文件的一种方法

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;

namespace ReaderExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            OleDbConnection ole = null;
            try
            {
                string strConn;
                //文件路径
                String filePath = "D:\\txts\\Book4.xlsx";
                //Excel 2007 以上版本连接字符串
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 12.0 Xml;";
                //建立连接
                ole = new OleDbConnection(strConn);
                ole.Open();
                //表名
                string sql = "select * from [Sheet1$]";
                //建立数据适配器
                OleDbDataAdapter oleExcel = new OleDbDataAdapter(sql, ole);
                //新建数据集
                DataSet dsExcel = new DataSet();
                //把数据适配器中的数据读到数据集中的一个表中(表名为sheet1)
                oleExcel.Fill(dsExcel, "Sheet1");


                DataTable tb= dsExcel.Tables["Sheet1"];


                foreach (DataRow row in tb.Rows)
                {
                    Console.WriteLine(row[3]);
                }

                foreach (DataColumn column in tb.Columns)
                {
                    Console.WriteLine(column.);
                }



                // Console.WriteLine(tb.Rows);
                //tb.Rows[1][2];
                //      Console.WriteLine(dsExcel.Tables [0]);
                Console.WriteLine(tb.Rows[3][10]);
                Console.WriteLine(tb.Columns.Count );
               
                Console.WriteLine(tb.Rows.Count);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                ole.Close();
            }
            Console.ReadKey();      
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37954004/article/details/80691853
今日推荐