如何使用oledb读取excel中的所有列并在控制台中显示所有列

时间:2012-10-14 15:35:39

标签: excel c#-4.0 oledb

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


namespace ReadingExcel
{
    public class Program
    {
        public static void Main(string[] k)
        {

            string connectionString = @"Provider= Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\SaiKiran\Desktop\MyExl.xlsx;Extended Properties=Excel 12.0 Xml";

            //Create the connection

            System.Data.OleDb.OleDbConnection excelConnection = new System.Data.OleDb.OleDbConnection(connectionString);
            string excelQuery = @"Select * from [Sheet1$]";
            //string excelQuery1 = @"Select * from [Sheet1$]";
            System.Data.OleDb.OleDbCommand excelCommand = new System.Data.OleDb.OleDbCommand(excelQuery, excelConnection);
            excelConnection.Open();
            System.Data.OleDb.OleDbDataReader excelReader;
            excelReader = excelCommand.ExecuteReader();

            while (excelReader.Read())
            {
                //Globals.Sheet1.Cells[1, 3] = "Set my data";
                    Console.WriteLine("id={0}", excelReader[0].ToString());
                    Console.ReadLine();

            }
            excelConnection.Close();

        }
    }
}

我的excel中的列A,B,C是.xlsx格式。现在的代码我现在只能读一列。请告诉我循环或读取所有列的内容。

1 个答案:

答案 0 :(得分:0)

回答太迟了。但是它可以帮助寻找类似解决方案的人。

这是给出的一个解决方案: http://support.microsoft.com/kb/302096