Oledb read from excel

В этой статье опишу как прочитать Excel с помощью OleDB.

Иногда бывает нужно вытянуть таблицу из Excel документа, записать в DataTable для последующей обработки.

Не всегда это удобно делать с помощью циклов, поэтому будем считывать таблицы, содержащиеся в документе и запрашивать из них данные с помощью SQL запросов.

oledb C#

Определение строки подключения

Для разных версий Excel будут свои строки подключения.

Строка подключения для Excel 2007 и более новых версий

//Можно использовать, если количество строк менее 65536
Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'

//Если строк больше 65536
Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties="Excel 12.0 Xml;HDR=YES";

Для работы с данными версиями необходимо установить Microsoft Access Database Engine 2010 Redistributable.

Так же C# может выбрасывать исключения по поводу недостающих драйверов. В этом случае необходимо скачать соответствующие драйверы с сайта Microsoft.

Строка подключения для более ранних версий

Строка подключения для Excel версии 2003 может иметь такой вид:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'

Если C# выбросит исключение, скачайте недостающий драйвер, Visual Studio подскажет, какой.

Как сделать SQL запрос из таблицы Excel

Для выполнения SQL запроса нужно найти таблицу в документе и выполнить к ней запрос:

//Объявляем OleDB соединение
using(OleDbConnection conn = new OleDbConnection(conStr))
{
  //Открываем подключение
  conn.Open();
  //Запрашиваем таблицы
  DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  DataRow schemaRow = schemaTable.Rows[0];
  //Получаеи имя таблицы
  string sheet = schemaRow["TABLE_NAME"].ToString();
  //Объявляем команду
  OleDbCommand com = conn.CreateCommand();
  //Создаем SQL запрос
  com.CommandText = "SELECT * FROM [" + sheet + "]";
  //Выполняем SQL запрос
  OleDbDataReader reader = com.ExecuteReader();
  //Записываем результат в DataTable
  DataTable table = new DataTable();
  table.Load(reader);
  //Выводим DataTable в таблицу на форму (если нужно)
  gridControl1.DataSource = table;
}

На этом шаге мы имеем считанные данные из Excel документа в DataTable.

После обработки данных можно сохранить данные в другой документ или оформить сводную таблицу.

Как работать с Excel с помощью C# обсуждалось ранее.

Так же можете посмотреть, как работать со сводными таблицами в Excel с помощью C# и редактора VBA, встроенного в Excel.


Просмотрено:
7 446

I am using OLEDB Data Provider to read excel file, but the problem is that in excel sheet some cloumn has an invalid value for example instead of number string is there,
When I read this invalid value I get an empty string instead of actual value.

enter image description here

for above screenshot when i read value john getting empty string.

So is there any way to read this invalid value?

Any help will be appreciated.

The Code is to read excel file

private DataTable ReadExcelFile(string sheetName, string path)
{

    using (OleDbConnection conn = new OleDbConnection())
    {
        DataTable dt = new DataTable();
        string Import_FileName = path;
        string fileExtension = Path.GetExtension(Import_FileName);
        if (fileExtension == ".xls")
            conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
        if (fileExtension == ".xlsx")
            conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
        using (OleDbCommand comm = new OleDbCommand())
        {
            comm.CommandText = "Select * from [" + sheetName + "$]";

            comm.Connection = conn;

            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = comm;
                da.Fill(dt);
                return dt;
            }

        }
    }
}

asked Aug 29, 2013 at 12:53

Gajendra's user avatar

GajendraGajendra

1,2911 gold badge19 silver badges32 bronze badges

0

This worked for me

        using (OleDbConnection conn = new OleDbConnection())
        {
            DataTable dt = new DataTable();
            conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path
            + ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;MAXSCANROWS=0'";
            using (OleDbCommand comm = new OleDbCommand())
            {
                comm.CommandText = "Select * from [" + sheetName + "$]";
                comm.Connection = conn;
                using (OleDbDataAdapter da = new OleDbDataAdapter())
                {
                    da.SelectCommand = comm;
                    da.Fill(dt);
                    return dt;
                }
            }
        }

The MAXSCANROWS=0 overrides the registry default and scans all rows before determining types. IMEX=1 still needs to be included.

For example, given this table:

Header | Header
------ | ------
Cell1  | 2456354
Cell2  | 2456354
Cell3  | 2456354
Cell4  | 2456354
Cell5  | 2456354
Cell6  | 2456354
Cell7  | 2456354
Cell8  | 2456354
Cell9  | A5341

The following connection strings will lose A5341

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path 
   + ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'"

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path
   + ";Extended Properties='Excel 12.0 Xml;HDR=YES;MAXSCANROWS=0'"

But it works when it has both.

Hans Kesting's user avatar

Hans Kesting

37.6k9 gold badges83 silver badges111 bronze badges

answered Oct 20, 2016 at 20:59

Adam's user avatar

AdamAdam

1,8051 gold badge17 silver badges24 bronze badges

You need to set value for TypeGuessRows Registry key to 0, this way driver will set data type based on all column values instead of first 8 (default).

The location of the key differs from version to version of driver, you can easily Google it based on your specific version. For example for Access Connectivity Engine 2007 it would be

HKEY_LOCAL_MACHINESOFTWAREMicrosoftOffice12.0Access Connectivity EngineEnginesExcel

By the way, you do not need Jet to read XLS files, ACE is perfectly capable of this as well.

answered Aug 29, 2013 at 12:58

Yuriy Galanter's user avatar

Yuriy GalanterYuriy Galanter

38.5k13 gold badges68 silver badges129 bronze badges

3

Провайдеры данных

Для работы с Excel 2003 (.Xls) можно использовать провайдер Microsoft Jet OLE DB 4.0.

SELECT * FROM OPENROWSET(
	'Microsoft.Jet.OLEDB.4.0', 
	'Excel 12.0;Database=d:tmpTimeSheets.xlsx;HDR=YES;IMEX=1', 
	'SELECT * FROM [Sheet1$]');

Для работы с Excel 2007 (.Xlsx) — Microsoft ACE OLEDB 12.0.

SELECT * FROM OPENROWSET (
    'Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;Database=d:tmpTimeSheets.xlsx;HDR=YES;IMEX=1',
    'SELECT * FROM [Sheet1$]');

В Windows 10 открыть настройки источников данных ODBC можно написав «Источники данных ODBC» или через Панель управления Администрирование.

Extended Properties

  • HDR=YES|NO. HDR=YES означает, что первую строку листа, следует рассматривать как заголовки колонок. Т.о. значение из первой строки можно использовать как имена полей в sql запросах (любых: select, insert, update, delete).
  • IMEX=1|3. 1 — открыть соединение для чтения. 3 — для записи.

Создание Linked Server в Sql Server для доступа к Excel

EXEC sp_addLinkedServer
    @server= N'XLSX_2010',
    @srvproduct = N'Excel',
    @provider = N'Microsoft.ACE.OLEDB.12.0',
    @datasrc = N'd:tmpTimeSheets.xlsx',
    @provstr = N'Excel 12.0; HDR=Yes';
GO

После создания связанного сервера можно будет просмотреть имена доступных листов.

Затем, чтобы обратиться к сервису:

SELECT * FROM OPENQUERY (XLSX_2010, 'Select * from [Sheet1$]')
или
SELECT * FROM [XLSX_2010]...[Лист1$]

Обращение к лиcтам, диапазонам, полям

Для обращения к листу из SQL запроса нужно использовать имя листа, например: [Sheet1$] или [Лист1$]. Обращение к диапазону: [Sheet1$A16:F16].

Вставка данных в произвольное место

Примеры указания диапазона при вставке строк (insert)

  • [table1$B4:E20]
  • [table1$S4:U]
  • [table1$F:G]

При вставке должны выполняться следующие условия:

  • Первая строчка указанного диапазона дожна входить в диапазон ячеек с данными. Чтобы создать на листе диапазон с данными достаточно в углах некоторого прямоугольного диапазона (в левом верхнем и правом нижнем) вписать значение (C4:I7 на скриншоте). Т.е. сама первая строчка указанного в insert диапазона данные содержать не обязана, достаточно, чтобы она просто входила в такой диапазон. Иначе возникнет ошибка "This table contains cells that are outside the range of cells defined in this spreadsheet"
  • Хвост диапазона должен содержать пустые строки (хотя бы одну).

Пример: Дан лист, где заполнены только 2 ячейки: C4, I7. После выполнения команды INSERT INTO [table1$E6:G] VALUES(2, 'FF','2014-01-03') результат будет как на скриншоте. Поясним: строка E6:G6 является первой строкой диапазона для вставки. Она входит в заполненный диапазон C4:I7. Поэтому данные были вставлены на следующей пустой строке — 8. Из этого примера становится ясно, что через OleDb нельзя работать с несколькими независимыми диапазонами на одном листе, используя вставку (update будет работать).

Insert

Ошибки

  • System.Data.OleDb.OleDbException (0x80004005): Operation must use an updateable query. Соединение открыто для чтение, при этом происходит попытка внести изменения (выполнить insert, update или delete). Решение: открыть соединение для записи, установив свойство провайдера в строке соединения IMEX=3 (см. выше).
  • System.Data.OleDb.OleDbException (0x80004005): "This table contains cells that are outside the range of cells defined in this spreadsheet". Такая ошибка возникает при подпытке обновить (update) или вставить (insert) значения в диапазоне, в котором отсутствуют данные на листе.
    1. Если нужно произвести запись в определенные ячейки инструкцией update, то

Ссылки

  • https://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB
  • https://stackoverflow.com/questions/36987636/cannot-create-an-instance-of-ole-db-provider-microsoft-jet-oledb-4-0-for-linked
  • https://stackoverflow.com/questions/26267224/the-ole-db-provider-microsoft-ace-oledb-12-0-for-linked-server-null
  • http://www.ashishblog.com/importexport-excel-xlsx-or-xls-file-into-sql-server/
  • https://yoursandmyideas.com/2011/02/05/how-to-read-or-write-excel-file-using-ace-oledb-data-provider/
  • https://stackoverflow.com/questions/46373895/how-to-open-a-huge-excel-file-efficiently Несколько способов открыть большой Excel файл, в т.ч. с помощью OleDb.

Whether you are working on Windows or on Web or on Console application, at one stage we need to process data and excel file is widely used for it, so in previous article, we have explained about creating excel in C# without interop but in this article, I am going to provide you code to open and read excel file (.xls or .xlsx) in C# line by line in Console application using OLEDB or EPPlus or Interop (all 3 methods), you can use the same code C# code to fill ASP.NET GridView or MVC application table.

So, let’s get started with it.

Step 1: Create a new Console applicaiton in your Visual Studio, by navigating to File->New->Project-> Select «Windows Classic dekstop» from left-pane & «Console-App» from right-pane -> Provide a name to your application «CSharpReadExcelFile» -> Click «OK»

c-sharp-read-excel-min.png

Step 2: Now we have our Console application and we need to add C# code using OLEDB to read excel file, for that we would need connection string with the source URL of excel file.

In the given example as I am using .XLS excel file, here is my connection string

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Sample1.xls; Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'";

For Excel 97-2003 Format we can use “Microsoft Jet OLEDB Driver 4.0”, while for the Connection String for Excel 2007 Format (.XLSX), we can use “Microsoft Ace OLEDB Driver 12.0” and it’s connection string would be as below

 string connString = "Provider= Microsoft.ACE.OLEDB.12.0;" + "Data Source=Sample1.xlsx" + ";Extended Properties='Excel 8.0;HDR=Yes'";

In the above Connection string’s you may see extended properties HDR=Yes & HDR =No

Use HDR=YES if first excel row contains headers, alternatively,use HDR=NO when your excel’s first row is not headers and it’s data.

Now, we have connection string , we need to create connection using OLEDB and open it

             // Create the connection object
            OleDbConnection oledbConn = new OleDbConnection(connString);
           
            // Open connection
            oledbConn.Open();

Read the excel file using OLEDB connection and fill it in dataset

  //here sheet name is Sample-spreadsheet-file, usually it is Sheet1, Sheet2 etc..
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sample-spreadsheet-file$]", oledbConn);

                // Create new OleDbDataAdapter
                OleDbDataAdapter oleda = new OleDbDataAdapter();

                oleda.SelectCommand = cmd;

                // Create a DataSet which will hold the data extracted from the worksheet.
                DataSet ds = new DataSet();

                // Fill the DataSet from the data extracted from the worksheet.
                oleda.Fill(ds, "Employees");

in the above code Sample-spreadsheet-file is the name of Sheet.

Note: With the help of sheet name, you can refer to Excel data, you need to use ‘$’ with sheet name, e.g. Select * from [Sheet1$]

Now loop through each row of excel sheet and print it in Console app

 //loop through each row
                foreach(var m in ds.Tables[0].DefaultView)
                {
                    Console.WriteLine(((System.Data.DataRowView)m).Row.ItemArray[0] +" "+((System.Data.DataRowView)m).Row.ItemArray[1] +" "+((System.Data.DataRowView)m).Row.ItemArray[2]);

                }

If you are using ASP.NET, you can bind it with Grid View using below code instead of printing it

            // Bind the data to the GridView
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();

Now, we have discussed each step, suppose this is out Excel file

/sample-xls-file-read-csharp-min.png

and ese the code below in your Console application, build and execute it.

using System;
using System.Data;
using System.Data.OleDb;


namespace CSharpReadExcelFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //this is the connection string which has OLDB 4.0 Connection and Source URL of file
            //use HDR=YES if first excel row contains headers, HDR=NO means your excel's first row is not headers and it's data.
            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Sample1.xls; Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'";
          

            // Create the connection object
            OleDbConnection oledbConn = new OleDbConnection(connString);
            try
            {
                // Open connection
                oledbConn.Open();

                // Create OleDbCommand object and select data from worksheet Sample-spreadsheet-file
                //here sheet name is Sample-spreadsheet-file, usually it is Sheet1, Sheet2 etc..
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sample-spreadsheet-file$]", oledbConn);

                // Create new OleDbDataAdapter
                OleDbDataAdapter oleda = new OleDbDataAdapter();

                oleda.SelectCommand = cmd;

                // Create a DataSet which will hold the data extracted from the worksheet.
                DataSet ds = new DataSet();

                // Fill the DataSet from the data extracted from the worksheet.
                oleda.Fill(ds, "Employees");

                //loop through each row
                foreach(var m in ds.Tables[0].DefaultView)
                {
                    Console.WriteLine(((System.Data.DataRowView)m).Row.ItemArray[0] +" "+((System.Data.DataRowView)m).Row.ItemArray[1] +" "+((System.Data.DataRowView)m).Row.ItemArray[2]);

                }
           
            }
            catch (Exception e)
            {
                Console.WriteLine("Error :" + e.Message);
            }
            finally
            {
                // Close connection
                oledbConn.Close();
            }
        }
    }
}

Output of the above code will be as below

csharp-read-excel-file-xls-min.png

Now, if you are working on 64 bit operating system, you may get this error «The ‘Microsoft.Jet.OLEDB.4.0’ provider is not registered on the local machine.«.

Resolving this error: If your application is Desktop based, compile your EXE with x86 CPU (Menu Tools, Options, select Projects And Solutions, check the show advanced build configurations. Now in the Build Menu you will be able to go to the Config Manager and set output to x86.)

If your application is web based, then Enable ’32-Bit Applications’ in application pool.

On IIS, change the «Enable 32-bit Applications» setting to True, in the Advanced Settings for the Application Pool.

Disadvantage of using OLEDB for Excel

With OLEDB, you cannot format data that you inserted/updated in EXCEL sheet but Interop can do it efficiently. You cannot perform any mathematical operation or working on graphs using OLEDB, but it is really a good way to insert/update data in EXCEL where no Excel application is installed.

Reading Excel file using EPPlus

If you don’t want to use OleDb, you can try using EPPlus Nuget package based solution.

For this, you would have to install EPPlus, so navigate to «Tools»-> «Nuget package manager»-> «Manage Nuget for this solution» -> Select «Browse» tab and search for «EPPlus», then install the nuget package.

c-sharp-read-excel-file-epplus-example

Once you have installed the package, in your Console application «Program.cs», you can use the code below

using OfficeOpenXml;
using System;
using System.IO;


namespace ReadExcelInCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //provide file path
            FileInfo existingFile = new FileInfo(@"D:sample_XLSX.xlsx");
            //use EPPlus
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                //get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int colCount = worksheet.Dimension.End.Column;  //get Column Count
                int rowCount = worksheet.Dimension.End.Row;     //get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int col = 1; col <= colCount; col++)
                    {
                        //Print data, based on row and columns position
                        Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
                    }
                }
            }
        }
    }
}

Here is the image, which shows console application output with sample excel file (.xlsx), we are using .xlsx file here for reading in C# using EPPlus

epplus-sample-read-excel-c-sharp-min.png

You can use above EPPlus example to work in .NET Core C# also, to read excel file in .NET Core.

Read Excel using MS Office Interop

You can also read Excel file in C# using MS Office Interop easily.

First you will have to add reference for «Microsoft.Office.Interop.Excel«, so in your Console, Windows or Web-Application, right-click on «Reference» and then in «Assemblies» search for «Microsoft.Office.Interop.Excel»

read-excel-ms-office-csharp.png

So, here is the C# Code for it, considering we have sample XLSX file as above

using Microsoft.Office.Interop.Excel;
using System;

namespace ReadExcelCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Application excelApp = new Application();
            if (excelApp != null)
            {
                Workbook excelWorkbook = excelApp.Workbooks.Open(@"D:sample_XLSX.xlsx", 0, true, 5, "", "", true, XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
                Worksheet excelWorksheet = (Worksheet)excelWorkbook.Sheets[1];

                Range excelRange = excelWorksheet.UsedRange;
                int rowCount = excelRange.Rows.Count;
                int colCount = excelRange.Columns.Count;
                //get an object array of all of the cells in the worksheet (their values)
                object[,] valueArray = (object[,])excelRange.get_Value(
                            XlRangeValueDataType.xlRangeValueDefault);

                for (int i = 1; i <= rowCount; i++)
                {
                    for (int j = 1; j <= colCount; j++)
                    {
                     

                        Console.WriteLine(valueArray[i, j].ToString());
                    }
                }

                excelWorkbook.Close();
                excelApp.Quit();
            }
        }
    }
}

Output:

read-excel-csharp-interop.png

As you can see we have used Interop to open and read excel rows/columns, one of the drawbacks of using MS office Interop is that you need it installed on Server also.

You may also like to read:

Read Excel file and import data into GridView using Datatable in ASP.NET

Read file in C# ( Text file example using Console Application )

That’s it, feel free to provide your feedback in the below comment’s section.

Here I am explaining how to read excel sheet and import it using OLEDB Data Provider Connection and C# .Net. Excel Workbook is just like database with sheets corresponding to tables. See the mapping below.

Database   <—————>    Excel Workbook

Sheet        <—————->    Table

Connection String for Excel 97-2003 Format (.XLS)

For Excel 97-2003 format Microsoft Jet OLEDB Driver 4.0 is used. A sample connection string as follows.

«Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Book1.xls;Extended Properties=’Excel 8.0;HDR=Yes'»

 Connection String for Excel 2007 Format (.XLSX)

For Excel 2007 format the new Microsoft Ace OLEDB Driver 4.0 is used. A sample connection string as follows.

«Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:Book1.xlsx;Extended Properties=’Excel 8.0;HDR=Yes'»

Rest everything is same for both versions. One thing to note Microsoft Ace OLEDB Driver 12.0 works for both Excel 2003 and Excel 2007 formats.

You can specify whether your Excel file has Headers or not using the HDR property.

When HDR is set to Yes the First Row is considered as the Header of the Excel file.

For this tutorial I have used the following Excel Sheet

ID

Name

1

John

2

Smith

3

Rob

Establish a Connection

String strExcelConn = «Provider=Microsoft.Jet.OLEDB.4.0;»

+ «Data Source=Book1.xls;»

+ «Extended Properties=’Excel 8.0;HDR=Yes'»;

OleDbConnection connExcel = new OleDbConnection(strExcelConn);

OleDbCommand cmdExcel = new OleDbCommand();

cmdExcel.Connection = connExcel;

  

Accessing Sheets

 

connExcel.Open();

DataTable dtExcelSchema;

dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

connExcel.Close();

The dtExcelSchema contains all the Sheets present in your Excel Workbook

You access them in the following way

string sheetName = dtExcelSchema.Rows[0][«TABLE_NAME»];

This will give the name of the first sheet. i.e. Sheet1$

Running a Select Query by Specifying Column Names

DataSet ds = new DataSet();

string SheetName = dtExcelSchema.Rows[0][«TABLE_NAME»].ToString();

cmdExcel.CommandText = «SELECT ID, Name From [« + SheetName + «]»;

da.SelectCommand = cmdExcel;

da.Fill(ds);

Note the above query will only work when Header Row is present in the Excel Sheet.

XML Output of the Query

<?xml version=«1.0« standalone=«yes«?>

<NewDataSet>

  <Table>

    <ID>1</ID>

    <Name>John</Name>

  </Table>

  <Table>

    <ID>2</ID>

    <Name>Smith</Name>

  </Table>

  <Table>

    <ID>3</ID>

    <Name>Rob</Name>

  </Table>

</NewDataSet>

Running a Query without Specifying Column Names

string SheetName = dtExcelSchema.Rows[0][«TABLE_NAME»].ToString();

cmdExcel.CommandText = «SELECT * From [« + SheetName + «]»;

da.SelectCommand = cmdExcel;

da.Fill(ds);

connExcel.Close();

Above query will work in both cases if Header row is specified and when not specified

Output of the Above Query with Header = Yes

<?xml version=«1.0« standalone=«yes«?>

<NewDataSet>

  <Table>

    <ID>1</ID>

    <Name>John</Name>

  </Table>

  <Table>

    <ID>2</ID>

    <Name>Smith</Name>

  </Table>

  <Table>

    <ID>3</ID>

    <Name>Rob</Name>

  </Table>

</NewDataSet>

Output of the Above Query with Header = No

<?xml version=«1.0« standalone=«yes«?>

<NewDataSet>

  <Table>

    <F2>Name</F2>

  </Table>

  <Table>

    <F1>1</F1>

    <F2>John</F2>

  </Table>

  <Table>

    <F1>2</F1>

    <F2>Rob</F2>

  </Table>

  <Table>

    <F1>3</F1>

    <F2>Smith</F2>

  </Table>

</NewDataSet>

Running a Query on a Range of Cells

string SheetName = dtExcelSchema.Rows[0][«TABLE_NAME»].ToString();

cmdExcel.CommandText = «SELECT * From [« + SheetName + «A3:B5]»;

da.SelectCommand = cmdExcel;

da.Fill(ds);

connExcel.Close();

Many times you need to select all data from a range of Cells. The above query selects all the data within the cell range A3:B5

Output of the Above Query

<?xml version=«1.0« standalone=«yes«?>

<NewDataSet>

  <Table>

    <F1>2</F1>

    <F2>Rob</F2>

  </Table>

  <Table>

    <F1>3</F1>

    <F2>Smith</F2>

  </Table>

</NewDataSet>

You can download the sample source code here.

ReadExcel.zip (10.37 kb)

  • Remove From My Forums
  • Question

  • Hi

    Can anyone help me how to read values in Excel in C# . So that Once I read I can send them to DataBase. My excel file Test.xls in («C:»)

    Thanks
    Doss

Answers

  • His Doss, Create a reference in your project to Excel Objects Library.  The excel object library can be added in the COM tab of adding reference dialog. I hope the following code in your menu click event method will help you a lot to achieve your need.  this.openFileDialog1.FileName = «*.xls»;
     
    if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
       {
          Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
             openFileDialog1.FileName, 0, true, 5,
              «», «»,
    true, Excel.XlPlatform.xlWindows, «t», false, false,
              0,
    true);
     
         Excel.Sheets sheets = theWorkbook.Worksheets;
         Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
         for (int i = 1; i <= 10; i++)
         {
         Excel.Range range = worksheet.get_Range(«A»+i.ToString(), «J» + i.ToString());
         System.Array myvalues = (System.Array)range.Cells.Value;

         string[] strArray = ConvertToStringArray(myvalues);
         
    }
    }

    Cheers,
    Daya Anand, PSPIndia

  • If you don’t want to use the Excel COM objects, you can use OleDb. It takes a little setup in your Excel document. Basically, you need to define «named objects» in Excel that are synonymous to tables in a database. The first row of the named object are the column headers. To set up a named object, first select the range of cells (your «table,» with the first row being the column headers), then go to menu Insert->Names->Define. Name your object and press «Add.» Now you have an object which can be read by ADO.NET.

    Now for the C# (this example assumes I have an Excel file at C:Book1.xls and a named object in this workbook called «MyObject»):


    using System.Data;
    using System.Data.OleDb;

    OleDbConnection con = new OleDbConnection(@»Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Book1.xls;Extended Properties=Excel 8.0″);
    OleDbDataAdapter da = new OleDbDataAdapter(«select * from MyObject», con);
    DataTable dt = new DataTable();
    da.Fill(dt);

     

    You can use SQL to query the data in your named object.

  • You can read data from Excel using the JET OLEDB provider. See the URL below 
    for the necessary connection string, and a link to a KB article with further 
    information ...
    
    http://www.carlprothman.net/Default.aspx?tabid=87#OLEDBProviderForMicrosoftJetExcel
    
    -- 
    Brendan Reynolds
    
     wrote in message 
    news:9226766e-a1d5-400c-8d3c-8ffc566bec50@discussions.microsoft.com...
    > Hi
    >
    > Can anyone help me how to read values in Excel in C# . So that Once I
    > read I can send them to DataBase. My excel file Test.xls in ("C:")
    >
    > Thanks
    > Doss
    > 
    
    
    
  • If you are using a dynamically generated excel file then you can use the following:

    Excel.Sheets sheets = m_Excel.Worksheets;

    Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);

    System.Array myvalues;

    Excel.Range range = worksheet.get_Range(«A1», «E1».ToString());

    myvalues = (System.Array)range.Cells.Value;


    Thanks

Like this post? Please share to your friends:
  • Oledb provider для excel
  • Oledb provider for excel 64 bit
  • Oledb excel extended properties
  • Oledb excel connection string
  • Oledb data provider excel