C# Excel解析

***

Excel C# 解析


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

namespace ExcelAnalyze
{
    class Program
    {
        static void Main(string[] args)
        {
            string strExcelPath = "装备信息.xls";
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelPath + ";" +
                                      "Extended Properties=\"Excel 8.0;HDR=yes;IMEX=1;\"";
            //string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelPath + ";" +"Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"";
            //1.创建连接到数据源的对象
            OleDbConnection connection = new OleDbConnection(connectionString);
            //2.打开连接
            connection.Open();
            //3.查询
            string sql = "select * from [Sheet1$]";
            OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connection);//查询结果就是一个表格
            //4.查询完数据放到DataSet对象里面
            DataSet dataSet = new DataSet();//用来存放DataTable
            adapter.Fill(dataSet);
            connection.Close();//保存完之后关闭连接
            //5.取数据
            DataTableCollection dataTableCollection =  dataSet.Tables;//获取当前集合中所有的表格
            DataTable table =  dataTableCollection[0];//因为我们只往DataSet里面放置了一条表格 所以用索引为0取得他的第一个表格
            //6.取得表格中的数据  也就是取得表格的所有行  用行来遍历
            DataRowCollection rowRowCollection  = table.Rows;
            foreach (DataRow row in rowRowCollection)
            {
                //取得row中前8列的数据索引0到7
                for (int i = 0; i < 8; i++)
                {
                    Console.Write(row[i] + " ");
                }
                    Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}

原创文章 37 获赞 11 访问量 2799

猜你喜欢

转载自blog.csdn.net/qq_39691716/article/details/83758398