I have a class ParseXLS(string name, string driveLincence, string sex)
My .xls looks like :
Name | Drive Licence | Sex
A - Y - M
B - N - F
I want to read a big .xls and put all this data inside my class.
To read my .xls i used :
OleDbDataReader reader;
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
xlsFilePath + ";Extended Properties=Excel 8.0");
OleDbCommand command = new OleDbCommand("select * from [sheet1$]", con);
con.Open();
But i don't know how to obtain a List or ObservableCollection..
I found many hard solutions, lot of code, and not clear for me, i hope someone can help me with an easy solution.
Thanks in advance
You can load the data into a DataTable:
var results = new DataTable();
using(var con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ xlsFilePath + ";Extended Properties=Excel 8.0"))
{
var command = new OleDbCommand("select * from [sheet1$]", con);
con.Open();
var adapter = new OleDbDataAdapter(command);
adapter.Fill(results);
}
And from there, loop through the results and use the data however you need to:
foreach(DataRow row in results)
{
var name = row["name"].ToString();
var driversLicense = row["Drive Licence"].ToString();
var sex = row["Sex"].ToString();
//Do what you need
}
An alternative is to use a 3rd party library like EPPlus.
Related
I need your help. I have two excel files and I want to show them into datagridview. I found a problem that datagridview just shows one of my data not all. I want to show data like these :
These are my data from [Sheet1$]
WSID Lokasi Saldo
1234 A 200
5678 B 300
And these are my data from [Data$]
WSID Tipe Mesin Lokasi
1234 MF A
5678 MF B
9876 CRM C
If I press radiobutton MF, data which will be shown is data that has Tipe Mesin value of MF. Actually it should be shown 1234 and 5678 but it just show 5678. Can anyone help me ?
private void TampilDataSaldo()
{
RadioButton[] radiobtn = new RadioButton[] { MFRB, CRMRB };
string dir = LokasiSaldo.Text;
konek.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dir + ";Extended Properties='Excel 12.0 xml;HDR=YES;IMEX=1'";
koneksi.ConnectionString = string koneksi = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Dokumen\Alfon\Kerja\BCA\Program\Program-Pengisian-Uang-ATM-BCA-SOY\Program-Pengisian-Uang-ATM-BCA-SOY\bin\x86\Debug\ATM SLA SURABAYA.xlsx;Extended Properties='Excel 12.0 xml;HDR=YES';";
int saldo;
Int32.TryParse(SaldoTB.Text, out saldo);
int thresholdcas;
Int32.TryParse(SaldoTB.Text, out thresholdcas); //baca angka yang diinput di NominalBox dan ubah jadi integer
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();
OleDbCommand command1 = kon.CreateCommand();
if(radiobtn[0].Checked)
{
kon.Open();
command.CommandText = "select * from [Data$] where [Tipe Mesin] = '" + radiobtn[0].Text + "'";
OleDbDataReader reader = command.ExecuteReader();
while(reader.Read())
{
konek.Open();
System.Data.DataTable aksesdatatabel;
aksesdatatabel = konek.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
konek.Close();
OleDbCommand command2 = new OleDbCommand
(
"select WSID, Lokasi, Saldo from [Sheet1$] where WSID = '" + reader["WSID"].ToString() + "'", konek
);
DataSet coba = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command2);
adapter.Fill(coba);
var table = coba.Tables[0];
var view = new DataView(table);
view.RowFilter = string.Format("Saldo < '{0}'", thresholdcas);
ViewDataSaldoGV.DataSource = view;
}
kon.Close();
}
}
As the others have stated in the comments. You are looping through each item and rather than adding the data to a collection outside of the loop you are creating a new object each time.
You will want to move the dataset outside of the while loop, and simply add rows to it inside of the loop. This way you have a single collection that is added to, Rather then creating and not using multiple 1 record datasets
I am new to C# and I am trying to read an excel file with the following code
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath +
";Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(conStr))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using (OleDbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
I get the following error:
Sheet1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
Can anyone tell me whats I am doing wrong?
The name of excel sheet is sheet.xlsx
Thanks
The sheet name might not be the same as the filename, you can get the first sheet name by doing the following
First, get the schema
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
Then get the first sheets name
var sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
After you get your command, you can then fill a dataset and work with it's .Rows collection
var myDataSet = new DataSet();
command.Fill(myDataSet);
The sheetname is this
My excel simulation needs to be imported into C#, after which the table needs to be able to be refreshed. The simulation revolves around randomly generated numbers. The random numbers are the only columns that change, since I'm doing that manually. The surrounding columns should update with the random numbers. I have tried various things but no luck so far.
Also, as the code is now, the
adp.Update(excelDataSet);
command invokes the error "Update requires a valid UpdateCommand when passed DataRow collection with modified rows." The table is only loaded into the gridview at all when it is commented out.
Here is my code atm. Thanks in advance.
string fileName = #"C:\simulation.xlsx";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;READONLY=FALSE\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbCommand selectCommand = new OleDbCommand("select * from [SHEET1$]", con);
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
DataSet excelDataSet = new DataSet();
adp.Fill(excelDataSet);
for (int i = 0; i < 29; i++)
{
excelDataSet.Tables[0].Rows[i][1] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][6] = Math.Round(r.NextDouble(), 2);
excelDataSet.Tables[0].Rows[i][8] = Math.Round(r.NextDouble(), 2);
}
adp.Update(excelDataSet);
gridview.DataSource = excelDataSet.Tables[0];
con.Close();
Add a line that build a OleDbCommandBuilder
....
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
OleDbCommandBuilder cb = new OleDbCommandBuilder(adp);
adp.UpdateCommand = cb.GetUpdateCommand();
....
This will create the UpdateCommand in the OleDbDataAdapter for you, (can be used also for the InsertCommand and DeleteCommand)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am developing on web application that will get the excel file using FileUpload control in asp.net c#. Now when click on submit button, i want to insert the excel data into my database table. I have database in SQL-Server. The field of database table & excel file are same.I want to insert that excel's data into my database table. So how can i do this?
Others have mentioned using Excel interop to read the Excel file in the comments, but this is NOT safe to do for a web application that may have multiple users.
To get started, have a look at the Excel Data Reader project. I've used this several times for processing Excel files from a web application and it works quite well.
You can use OLEDB classes to read directly from Excel file using the Excel drivers in OleDbConnection. Get the data in a datatable and save it to database.
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\\testit.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
// Save your datatable records to DB as you prefer.
I've been testing NPOI as a replacement for another 3rd party Excel parsing library.
https://code.google.com/p/npoi/
So far it seems to work pretty well and have a very complete feature set. Of course, if all you need is very basic Excel data reading (and no writing), then the other DB connection style interfaces mentioned here should work well enough.
EDIT: added sample code
using( FileStream fs = new FileStream("file.xls", FileMode.Open, FileAccess.Read) )
{
HSSFWorkbook wb = new HSSFWorkbook(fs);
double value = wb.GetSheet("Sheet1").GetRow(1).GetCell(1).NumericCellValue;
// read other values as necessary.
}
try the following code . maybe its crude but it works
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\data\\exceltest.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
SqlConnection sqlc = new SqlConnection(#"server=.\SQLEXPRESS;user id=sa;pwd=windows;database=exceltest");
sqlc.Open();
SqlCommand cmd = new SqlCommand("select * from table1", sqlc);
SqlDataAdapter sda = new SqlDataAdapter("select * from table1", sqlc);
sda.InsertCommand = new SqlCommand("insert into table1", sqlc);
DataTable dbset = new DataTable();
da.Fill(dbset);
SqlCommand cmdinsert = new SqlCommand();
cmdinsert.Connection = sqlc;
foreach (DataRow dsrc in dt.Rows)
{
string insertcommand = "insert into table1" + dbset.TableName + " ";
string cols = "";
string vals = "";
DataRow dr = dbset.NewRow();
foreach (DataColumn clm in dt.Columns)
{
dr[clm.ColumnName] = dsrc[clm.ColumnName].ToString(); ;
if (cols.Length > 0)
{
cols += ",[" + clm.ColumnName+"]";
}
else
{
cols = "["+clm.ColumnName+"]";
}
if (vals.Length > 0)
{
vals += "," + "'" + dsrc[clm.ColumnName].ToString() + "'";
}
else
{
vals = "'" + dsrc[clm.ColumnName].ToString() + "'";
}
}
insertcommand += "(" + cols + ") values("+vals+")";
cmdinsert.CommandText = insertcommand;
cmdinsert.ExecuteNonQuery();
insertcommand = "";
}
sqlc.Close();
I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>