Read excel spreadsheet into a datatable - c#

I am using the below C# code in my program to read excel 97 - 2003 spreadsheet data into a datatable using oledbconnection and ran into the name does not exist in the current context.
DataTable rs = null;
string path = Path.GetFullPath(filePath);
odConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
odConnection.Open();
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dt = odConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = string.Empty;
if (dt != null)
{
sheetName = dt.Rows[0]["Sheet_Name"].ToString();
}
cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
oda = new OleDbDataAdapter(cmd);
oda.Fill(ds, "excelData");
rs = ds.Tables["excelData"];

Here is example how to get all columns and rows from special Sheet from xlsx file. This code takes all data from Sheet2 from xlsx file and fill the DataTable with that values.
Hopefully this will help you.
using System;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
DataTable rs = new DataTable();
using (var odConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\Users\IIG\Desktop\test.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
{
odConnection.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet2$]";
using (OleDbDataAdapter oleda = new OleDbDataAdapter(cmd))
{
oleda.Fill(rs);
}
}
odConnection.Close();
}
foreach(DataRow row in rs.Rows)
{
foreach(object item in row.ItemArray)
{
Console.Write(item +"\t");
}
Console.WriteLine();
}
}
}
}

Below line might be causing the issue -
if (dt != null)
{
sheetName = dt.Rows[0]["Sheet_Name"].ToString();
}
Try using
dt.Rows[0]["Table_name"].ToString();
This should return the name of the sheet.

Related

OleDb parameter to be used in from clause

I have the following code to read a CSV file and populate a DataTable:
string sql = #"SELECT * FROM [" + fileName + "]";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
}
This snipped works great, but code analysis complains about it (CA2100). The way I build the query string should be changed so I can use parameters.
I am trying to fix this, but it seems the usual OleDbParameter usage does not work. The query is built with the parameter name instead of its value:
string sql = #"SELECT * FROM #param";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
command.Parameters.Add(new OleDbParameter("#param", fileName));
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
}
Any ideas?

import data from multiple excel files into datagridview

I am getting list of excel files within specific directory as below
public void GetFilesList()
{
ListFiles = Directory.GetFiles(DefaultDirectory, "*.xlsx", SearchOption.AllDirectories);
foreach (string FilePath in ListFiles)
{
ImportExcel(FilePath);
}
}
then I am trying to add rows from each file within that directory into my datagridview as below
public void ImportExcel(string FilePath)
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";
OleDbConnection Conn = new OleDbConnection(ConnStr);
OleDbDataAdapter DA = new OleDbDataAdapter("select * from [Sheet1$]", Conn);
DataTable dt = new DataTable();
if (dataGridView1.Rows.Count == 0)
{
DA.Fill(dt);
dataGridView1.DataSource = dt;
//Calculate record counts
L_Total_Rows.Text = "count: " + dataGridView1.Rows.Count.ToString("n0");
Conn.Close();
}
else
{
foreach (DataRow dr in dt.Rows)
{
dataGridView1.Rows.Add(dr);
dataGridView1.DataSource = dt;
}
}
}
my problem is that it import rows form one excel file only
it wont get into else condition it only get into the if condition then stops importing
another one question anyway to NOT use the sheet name at query [Sheet1$]? I don't know if it is possible the index of sheets ?
can I start importing the excel file form specific row like fourth row of excel file ?
How about you combine your result sets into one data table first:
DataTable dt = new DataTable();
using(OleDbDataAdapter a1 = new OleDbDataAdapter("select * from [Sheet1$]", Conn))
a1.Fill(dt);
using(OleDbDataAdapter a2 = new OleDbDataAdapter("select * from [Sheet1$]", Conn))
a2.Fill(dt);
the issue was solved by moving DataTable dt = new DataTable(); to the beginning of the class because each time I am calling ImportExcel(FilePath) method it will build new datatable so it will delete all old data and create new datatable and changed my method to below
public void ImportExcel(string FilePath)
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";
OleDbConnection Conn = new OleDbConnection(ConnStr);
OleDbDataAdapter DA = new OleDbDataAdapter("select * from [Sheet1$]", Conn);
DA.Fill(dt);
DGV_Data.DataSource = dt;
//Calculate record counts
L_Rows_Count.Text = "Count: " + (DGV_Data.Rows.Count - 1).ToString("n0");
Conn.Close();
}
now there is a small problem still annoying me which is it will insert an empty row at datagriview between each imported excel file

Displaying values of excel Workbook in DataGridView C#

I need some help displaying values of excel in datagridview.
i manage to display values but some of the values are missing(columns,and values of rows).i have 1000 rows in my excel file and the data grid view is only displaying 333 items in it. and i have 148 number of columns but it only display some of it. can someone tell me what the problem is.
here is my code:
public partial class MainBagsakan : Form
[enter image description here][1]
String WOmain=#"C:\Users\tjjtabije\Desktop\TestExcelUpdater\TestUnoREFARM.xlsx";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\t-jjtabije\\Desktop\\TestExcelUpdater\\TestUnoREFARM.xlsx;Extended Properties='Excel 12.0 Xml;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text'";
private void WorkOrderTab()
{
string filePath = Path.GetFullPath(WOmain);
string extension = Path.GetExtension(filePath);
string conStr, sheetName;
conStr = string.Empty;
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(Excel07ConString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
using (OleDbConnection con = new OleDbConnection(Excel07ConString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandText = "SELECT * [" +sheetName+ "]";
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
WorkLoadDisp.DataSource = dt;
label1.Text = dt.Rows.Count.ToString();
}
}
}
}
It is unnecessary to open and close the connection twice as you are with the two separate using clauses. The first one simply gets the name of a worksheet sort of, as a named range could also be returned. I simply put all the code into a single group and it seems to work as expected.
Added a missing FROM to the select statement:
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
The changes I made are below...
using (OleDbConnection con = new OleDbConnection(Excel07ConString)) {
using (OleDbCommand cmd = new OleDbCommand()) {
using (OleDbDataAdapter oda = new OleDbDataAdapter()) {
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
//con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
WorkLoadDisp.DataSource = dt;
label1.Text = dt.Rows.Count.ToString();
}
}
}
Hope this helps.

Why replace specific character in Column Name when Importing Excel to C# (WPF)

When import Microsoft Excel file to C# (WPF), specific characters in Column Names (Column Headers) will be replaced.
eg ! it becomes _, and . to #. How to stop it?
connectionString:
Provider=Microsoft.ACE.OLEDB.12.0; Data Source="+filePath+";Extended Properties="Excel 8.0;HDR=YES;CharacterSet=65001;";
And method:
public DataSet ImportExcel(string fileName)
{
tableList = null;
DataSet ds = new DataSet();
string connectionString = GetConnectionString(fileName);
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
// Get all Sheets in Excel File
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
tableList = new string[dtSheet.Rows.Count];
// Loop through all Sheets to get data
foreach (DataRow dr in dtSheet.Rows)
{
string sheetName = dr["TABLE_NAME"].ToString();
tableList[dtSheet.Rows.IndexOf(dr)] = sheetName;
Console.WriteLine("TABLE_NAME: " + sheetName);
if (!sheetName.EndsWith("$"))
continue;
// Get all rows from the Sheet
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
DataTable dt = new DataTable();
dt.TableName = sheetName;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
rowsCount += dt.Rows.Count;
ds.Tables.Add(dt);
}
cmd = null;
conn.Close();
}
return ds;
}
Basically you are limited to what characters are allowed in column names, these are letters, numbers and characters: ##$_ see here. The $ symbol and numbers aren't allowed to be the first character either.

Importing Any Excel Spreadsheet into a DataGridView - C#

I have a program that imports an excel spreadsheet into a datagridview. I have written the code as follows:
try
{
OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
connStringBuilder.DataSource = file;
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX1");
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connStringBuilder.ConnectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
data = new DataSet();
adapter.Fill(data);
dataGridView1.DataSource = data.Tables[0].DefaultView;
}
catch (IOException)
{
}
The line "selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";" takes the data from the sheet with that name. I was wondering how I could get this program to open an excel document with any sheet name. One that I may not know.
You can get all the sheets' names like so..
public string[] GetExcelSheetNames(string excelFileName)
{
OleDbConnection con = null;
DataTable dt = null;
String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
con= new OleDbConnection(conStr);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}

Categories

Resources