Using OleDB to read excel file in c#? - c#

I am building a program to read excel file into dataGridView.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
namespace pro1._0
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string sConnecStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:\\Copy_of_Acute_HCV_2008.xls" + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conObj = new OleDbConnection(sConnecStr);
conObj.Open();
OleDbCommand sqlCommand = new OleDbCommand("SELECT * FROM [Sheet1$]",conObj);
OleDbDataAdapter adaObj = new OleDbDataAdapter();
adaObj.SelectCommand = sqlCommand;
DataSet setObj = new DataSet();
adaObj.Fill(setObj);
conObj.Close();
dataGridView1.DataSource = setObj.Tables[0];
dataGridView1.Refresh();
}
}
}
The program runs fine when i use a small excel file but when i use a big excel file it gives me this error
An unhandled exception of type
'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: 'Sheet1$' is
not a valid name. Make sure that it
does not include invalid characters or
punctuation and that it is not too
long.
thanks
edit: i always use .xls files not .xlsx

protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
if ((txtFilePath.HasFile))
{
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string query = null;
string connString = "";
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();
if (strFileType == ".xls" || strFileType == ".xlsx")
{
txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
}
string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed) conn.Open();
string SpreadSheetName = "";
DataTable ExcelSheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
SpreadSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
query = "SELECT * FROM [" + SpreadSheetName + "]";
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, "tab1");
}
}
}

Related

How can read excel sheet 2016 using c# code

I am reading excel sheet using below code but that gives blank data table.
public static DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch(Exception ex) { }
}
return dtexcel;
}
It displays empty data table as below screenshot.
you forgot few things, like OleDbConnection.Open(); and using OleDbCommand
public DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string sheetName = "Sheet1$";
string conn = string.Empty;
DataTable dt = new DataTable();
if (fileExt.CompareTo(".xlsx") != 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
using ( OleDbCommand cmd = new OleDbCommand())
{
con.Open();
try
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
dt.TableName = sheetName;
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (Exception ex) { }
}
return dt;
}
try rhis code hope it help you
protected void btn_Click(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("File/" + filename));
string CurrentFilePath = Server.MapPath("File/" + filename);
string connectString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CurrentFilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
conn.Open();
DataTable Sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [" + sht + "]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
}
}
For me working following code
string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "").Replace("\\bin\\Release", "");
string fileLocation = filePath + ConfigurationManager.AppSettings["EmployeeDetailsFilePath"];
Stream inputStream = File.Open(fileLocation, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(inputStream);
reader.IsFirstRowAsColumnNames = true;
DataSet dataSet = reader.AsDataSet();
inputStream.Dispose();
reader.Dispose();
here must add reference of ExcelDataReader dll in your project.

syntax error at or near pgsl?

I am developing an asp.net web application and I would like to import a fichier excel to postgresql. I'm using this code but it gives me this error. Can you help me?
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1056: Unexpected character '$'
Line 74: quer = "INSERT INTO poi (num_route, pk, geom)
select num_route,pk_debut from [Sheet1$]";
Line 75: NpgsqlCommand cm = new NpgsqlCommand(quer, cnx); L
ine 76: reader = cm.ExecuteReader();
using System;
using System.Configuration;
using System.IO;
using System.Data;
using System.Drawing;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Text;
using System.Xml;
using Npgsql;
using System.Collections.Specialized;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblMessage.Text = "Please select an excel file first";
lblMessage.Visible = false;
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if ((txtFilePath.HasFile))
{
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string query = null;
string quer = null;
string connString = "";
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();
//Check file type
if (strFileType == ".xls" || strFileType == ".xlsx")
{
txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
}
else
{
lblMessage.Text = "Seuls les fichiers Excel autorisés";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
return;
}
string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
query = "SELECT num_route,pk_debut,pk_fin FROM [Sheet1$]";
NpgsqlConnection cnx = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=*****;Database=****;");
NpgsqlDataReader reader;
cnx.Open();
quer = "INSERT INTO poi (num_route, pk) select num_route,pk_debut from "Sheet1$"";
NpgsqlCommand cm = new NpgsqlCommand(quer, cnx);
reader = cm.ExecuteReader();
//Create the connection object
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Closed) conn.Open();
//Create the command object
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
grvExcelData.DataSource = ds.Tables[0];
grvExcelData.DataBind();
lblMessage.Text = "Les données récupérées avec succès! Total de lignes:" + ds.Tables[0].Rows.Count;
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = true;
da.Dispose();
conn.Close();
conn.Dispose();
}
else
{
lblMessage.Text = "S'il vous plaît sélectionner un fichier excel";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
}
}
}
I would suggest trying something like this
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
var Builder = new StringBuilder("INSERT INTO poi (num_route, pk) select num_route,pk_debut VALUES ");
bool first = true;
using (var conn = new OleDbConnection(connString))
{
if (conn.State == ConnectionState.Closed) conn.Open();
using (var cmd = new OleDbCommand("SELECT num_route,pk_debut,pk_fin FROM [Sheet1$]", conn))
using (var da = cmd.ExecuteReader())
{
while (da.Read())
{
if (!first) Builder.Append(",");
Builder.Append("(");
Console.WriteLine(da[0]);
Builder.Append(",");
Console.WriteLine(da[1]);
Builder.Append(",");
Console.WriteLine(da[2]);
Builder.Append(")");
first = false;
}
}
}
using (NpgsqlConnection cnx = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=*****;Database=****;"))
{
cnx.Open();
var quer = Builder.ToString();
using (NpgsqlCommand cm = new NpgsqlCommand(quer, cnx))
cm.ExecuteNonQuery();
}

how to Upload a excel file to sql database table using c# windows form application

I want to upload a excel file through windows form application in c# and want to import the data to database ( Mysql server). how can i do that??? I have created a form which requires me to upload a excel file into the mysql database . its an bulk insert data to database table.
My Excel File Contain columns like userid,password,first_name,last_name,user_group AND
MySql Database table(aster_users) Contain many columns like userid,password,first_name,last_name,user_group,queue,active,created_date,created_by,role ..
i need to upload that excel file to my database and other columns will get empty or null that's not a matter.
My Form design is
Here is My c# Code:
using MySql.Data.MySqlClient;
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace UploadFileToDatabase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String MyConString = "SERVER=******;" +
"DATABASE=dbs;" +
"UID=root;" +
"PASSWORD=pwsd;" + "Convert Zero Datetime = True";
private void BtnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text files | *.csv";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName;
fileName = dlg.FileName;
txtfilepath.Text = fileName;
}
}
private void btnUpload_Click(object sender, EventArgs e)
{
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtfileparth.Text + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
string sqlConnectionString = MyConString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.ColumnMappings.Add("[userid]", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.DestinationTableName = "aster_users";
bulkCopy.WriteToServer(dr);
MessageBox.Show("Upload Successfull!");
}
}
}
}
Here is how i tried.i got an error message like this
Additional information: External table is not in the expected format.
in this line connection.Open(); . How can this be Done?
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace IMPORT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String MyConString = "SERVER=******;" +
"DATABASE=db;" +
"UID=root;" +
"PASSWORD=pws;";
private void btnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
openfiledialog1.ShowDialog();
openfiledialog1.Filter = "allfiles|*.xls";
txtfilepath.Text = openfiledialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
string path = txtfilepath.Text;
string ConnString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties = Excel 8.0";
DataTable Data = new DataTable();
using (OleDbConnection conn =new OleDbConnection(ConnString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"SELECT * FROM [dataGridView1_Data$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
string ConnStr = MyConString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr))
{
bulkCopy.DestinationTableName = "TABLE NAME";
bulkCopy.ColumnMappings.Add("userid", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.WriteToServer(Data);
MessageBox.Show("UPLOAD SUCCESSFULLY");
}
}
}
An example found http://technico.qnownow.com/bulk-copy-data-from-excel-to-destination-db-using-sql-bulk-copy/.
And
ERROR: Additional information: External table is not in the expected format
ஆர்த்தி,
Use the Below Connection String Format
string File = sResponsedExcelFilePath;
string result = Path.GetFileName(sFilePath);
ExcelReaderConnString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + File +"\\"+ result + ";Extended Properties=Excel 12.0;");
Hope this works for you.
There is an awesome link that shows how to upload to c# datatable from excel...in case the link dies I am sharing the procedure....
The excel Connection Strings for diff versions:
private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
The File select event:
private void BtnSelectFile_Click(object sender, EventArgs e)
{
DataTable dt;
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Excel files | *.xls";
if (dlg.ShowDialog() == DialogResult.OK)
{
string filePath = dlg.FileName;
string extension = Path.GetExtension(filePath);
string conStr, sheetName;
conStr = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03
conStr = string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07 to later
conStr = string.Format(Excel07ConString, filePath);
break;
}
//Read Data from the Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
dt = new DataTable();
cmd.CommandText = "SELECT * From [Sheet1$]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
}
}
}
//Save the datatable to Database
string sqlConnectionString = MyConString;
if(dt != null)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.ColumnMappings.Add("[userid]", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.DestinationTableName = "aster_users";
bulkCopy.WriteToServer(dt);
MessageBox.Show("Upload Successfull!");
}
}
}
}
Then you can just save the datatable to mySql database which I hope you know how to do...If you can't then comment I'll try my best to help you. Thank You
Hope this helps....
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace IMPORT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String MyConString = "SERVER=******;" +
"DATABASE=db;" +
"UID=root;" +
"PASSWORD=pws;";
private void btnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
openfiledialog1.ShowDialog();
openfiledialog1.Filter = "allfiles|*.xls";
txtfilepath.Text = openfiledialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
string path = txtfilepath.Text;
string ConnString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties = Excel 8.0";
DataTable Data = new DataTable();
using (OleDbConnection conn =new OleDbConnection(ConnString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"SELECT * FROM [dataGridView1_Data$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
string ConnStr = MyConString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr))
{
bulkCopy.DestinationTableName = "TABLE NAME";
bulkCopy.ColumnMappings.Add("userid", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.WriteToServer(Data);
MessageBox.Show("UPLOAD SUCCESSFULLY");
}
}
}
I had huge problems trying to use either/both Jet and ACE.OLEDB providers. You could try this o/s library ClosedXML, which will import xlsx files: 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
Available via Nuget. It has its own wiki: https://github.com/ClosedXML/ClosedXML/wiki

in some computers some excel cells return back empty.can you help me?

I imported an Excel table to gridview. In my own notebook, everything is ok. However, in some notebooks Excel cells return back empty.
I'm using ASP.NET 4.0 and Visual C#
using System;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace ReadExcelInToDataSet
{
public partial class Default : System.Web.UI.Page
{
OleDbConnection oledbConn;
protected void Page_Load(object sender, EventArgs e)
{
try
{
string path = System.IO.Path.GetFullPath(Server.MapPath("~/Table_sverks.xls"));
if (Path.GetExtension(path) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(path) == ".xlsx")
{
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
grvData.DataSource = ds.Tables[0];
grvData.DataBind();
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
finally
{
oledbConn.Close();
}
}
}
}
I think it's the same issue in this question
OleDB & mixed Excel datatypes : missing data

read excel data line by line with c# .net

Does anyone know how can I read an excel file line by line in c#.
I found this code which will return the data from excel and display a grindview in c#. However, I just was wandering how to possibly read the data line by line on the server side instead?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace site
{
public partial class pgTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnImport_Click(object sender, EventArgs e)
{
string connString = "";
string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
string path = fileuploadExcel.PostedFile.FileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT [username],[age],[phone] FROM [Sheet1$]";
OleDbConnection conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
grvExcelData.DataSource = ds.Tables[0];
grvExcelData.DataBind();
da.Dispose();
conn.Close();
conn.Dispose();
}
}
}
Since Excel works with ranges you should first get the range of cells you would want to read. After that you can now browse through them using a for loop. You can see an example below:
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\myexcel.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
}
}
A more detailed explanation on this code block can be found here.
you can use OleDbDataReader as below
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var val1= reader[0].ToString();
}
reader.Close();
}
You must try this
string connectionString = "";
string strFileType = "Type";
string path = #"C:\Users\UserName\Downloads\";
string filename = "filename.xls";
if (fielname.Contains(.xls))
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + filename + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fielname.Contains(.xlsx)
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + filename + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT * FROM [SheetName$]";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
var lines = new List<string>();
while (reader.Read())
{
var fieldCount = reader.FieldCount;
var fieldIncrementor = 1;
var fields = new List<string>();
while (fieldCount >= fieldIncrementor)
{
fields.Add(reader[fieldIncrementor - 1].ToString());
fieldIncrementor++;
}
lines.Add(string.Join("\t", fields));
}
reader.Close();
}
I tried the solution with OleDbConnection but it didn't work because I didn't have something installed. Then I found this solution here and it worked like a charm:
https://www.codeproject.com/Tips/801032/Csharp-How-To-Read-xlsx-Excel-File-With-Lines-of
There you can download a small file Excel.dll, add it to your project and browse the excel files cell by cell.
A simple way to convert data table to enumerable of an object is using Json methods.
Per example, with simple method, using only dotnet libraries, you can convert data table to list of especific objects.
using System.Data;
private static IEnumerable<T> ConvertDataTable<T>(DataTable dataTable)
{
if (dataTable is null ||
!dataTable.AsEnumerable().Any())
{
return Enumerable.Empty<T>();
}
var data = dataTable.Rows.OfType<DataRow>()
.Select(row => dataTable.Columns.OfType<DataColumn>()
.ToDictionary(col => col.ColumnName, c => row[c]));
var jsonTextObject = System.Text.Json.JsonSerializer.Serialize(data);
return System.Text.Json.JsonSerializer.Deserialize<IEnumerable<T>>(jsonTextObject)
?? Enumerable.Empty<T>();
}

Categories

Resources