Even though I posted similar 2 articles in 2008, the code of that article was having few errors. So thought to put more complete post on this.
The code will read an Excel file using an OleDbConnection and will write the same data back to another Excel file. This will explain how to read and write to Excel files. One thing to remember when running this code is to make sure the source Excel file is open. Otherwise you will get an error similar to “External table is not in the expected format.”
Also note that there are few connection string parameters you can use while opening Excel files.
HDR = Yes – Use when first row contains column headers.
HDR = No - Use when first row contains data.
Excel xx.x – Use the following Table as a guide.
Parameter Value | Excel Version |
Excel 12.0 | Excel 2007 (Released in 2007) |
Excel 11.0 | Excel 2003 (Released in 2003) |
Excel 10.0 | Excel XP (Released in 2001) |
Excel 9.0 | Excel 2000 (Released in 1999) |
Excel 8.0 | Excel 97 (Released in 1997) |
IMEX=1 – Use this when you want to treat all your data in the file as text.
For example - >
Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";
To make the code to work properly you need to refer the Microsoft.Office.Interop.Excel assembly by adding a reference to your project.
- using System;
- using System.Data;
- using System.Windows.Forms;
- using System.Data.OleDb;
- using Microsoft.Office.Interop.Excel;
- namespace TestApp
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- openFileDialog1.ShowDialog();
- // Create an OLEDBConnection to connect to the Excel file.
- // I'm getting the required file by using a file dialog.
- // The @ symbol makes the string to contain any special characters inside the string without breaking the string.
- OleDbConnection dbConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openFileDialog1.FileName.ToString() + @";Extended Properties=""Excel 8.0;HDR=Yes;""");
- // Open the connection.
- dbConnection.Open();
- // Create a command object to work on the data.
- // Note that I have given the sheet name as [Sheet1$] to retrieve data from that named sheet in the particular Excel file.
- OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", dbConnection);
- // Creating a data reader to read data.
- OleDbDataReader dbReader = dbCommand.ExecuteReader();
- // If needed you can get the position of any column (e.g. Age), this will only work if you use HDR=Yes.
- int SearchingItem = dbReader.GetOrdinal("Age");
- // Create the Excel Application object.
- ApplicationClass ExcelApp = new ApplicationClass();
- // Set the visibility of the application.
- ExcelApp.Visible = true;
- // Create a new Excel Workbook.
- Workbook ExcelWorkbook = ExcelApp.Workbooks.Add(Type.Missing);
- // Create a new Excel Sheet.
- Worksheet ExcelSheet = (Worksheet)ExcelWorkbook.Sheets.Add(ExcelWorkbook.Sheets.get_Item(1), Type.Missing, 1, XlSheetType.xlWorksheet);
- // Will keep the current row index. This should start from 1 since the first row is 1.
- int CurrentRowIndex = 1;
- try
- {
- // Read through the data.
- while (dbReader.Read())
- {
- // Traverse through all the data columns.
- for (int i = 0; i < dbReader.VisibleFieldCount; i++)
- {
- ExcelSheet.Cells[CurrentRowIndex, i + 1] = dbReader.GetValue(i);
- }
- CurrentRowIndex++;
- }
- // Save the Excel sheet.
- // The @ symbol makes the string to contain any special characters inside the string without breaking the string.
- ExcelApp.Save(@"C:\Projects\Ex.xls");
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- }
- }
-