Import excel file using c#.net [duplicate] - winforms

This question already has answers here:
Reading Excel files from C#
(32 answers)
Closed 8 years ago.
I need to import an excel and have to do some process on it.
Those excel data should be retrieved using C#.
While i was googled, got confused.
Could anybody provide the c# code to achieve it?
Thanks in advance.

Using OleDB:
using System.Data.OleDb;
private void readExcel(string pExcelPath, string pSheetName)
{
DataTable sheet1 = new DataTable();
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = pExcelPath;
if (excelFirstRowIsHeader == true)
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
else
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=NO");
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
{
connection.Open();
string sqlQuery = #"SELECT * FROM [" + pSheetName + "]";
using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, connection))
{
adapter.Fill(sheet1);
excelData_dataGridView.DataSource = sheet1;
}
connection.Close();
}
}
This code supports Excel-files created with Excel 2007/2010.
The boolean excelFirstRowIsHeader is used to specifiy if your excel contains a header row (if the first row in your excel sheet is used a header)
You can also use Interop-Assembly to read an excel file, but therefor MS Excel must be installed.

Related

Importing data from Excel into SQL Server that has a different design in the template in Excel

I am developing a system that will import and export a data from Excel into a SQL Server database. I already done in exporting, my problem is in importing the template that I will import is different template that I exported. I know the code about importing because I learned it in google, but in my problem is, I can't get what I need. So allow me to show a screenshot about the template in my Excel.
That's the template, and my database design is like this:
So the PODATE and PORECEIVEDDATE there in database is equal to the PO DATE below in Excel and DELIVERYDATE is equal to ETD in Excel.
As of now I have a code here that will get only the above template and it will not get the whole data in Excel.
Here is my code:
public void ImportDataFromExcel(string excelFilePath)
{
string ssqltable = "tmp_100_POEntry_SF_sample";
//string myexceldataquery = "select PONO,PODATE,PORECEIVEDDATE,DELIVERYDATE,PARTCODE,QUANTITY,UNITCOST,TOTALAMOUNT,STOCKS,INCHARGE,CLIENT from [Sheet1$]";
string myexceldataquery = "select [PO NO],[PART CODE],QUANTITY,[UNIT COST],[TOTAL AMOUNT],STOCKS,[IN CHARGE],CLIENT from [Sheet1$]";
try
{
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + excelFilePath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(Common.connectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(Common.connectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
}
catch (Exception ex)
{ throw ex; }
}
That code is really have an error if I add the PODATE, PORECEIVEDDATE and DELIVERDATE. All I just want is to get the 3 remaining parameters value from Excel into the database.
I don't want to change the template in Excel because of some reason.
Please I badly need your help guys. I really appreciate it.

How to convert an Image to OLE object in VB.net [duplicate]

I have an Access .mdb database and I want to insert an image from an application developed in visual C# 2010. Pictures are stored in the database in the field of OLE-object.
After adding images directly in Access they are stored in the format of an Bitmap Image. These pictures can be opened in Access with a double-click.
I have the following code:
OdbcConnection Connection = new OdbcConnection();
...
sql = "INSERT INTO film (poster) VALUES (" ' " + Image.FromFile(textBox8.Text) + " ' ");";
//texbox are stored the picture name
OdbcCommand Command = new OdbcCommand(sql, Connection);
Command.ExecuteNonQuery();
The code works well, but Access stores the picture as binary data and it cannot be opened again in Access. Please tell me how to insert the image as a Bitmap Image. Thanks.
This is a somewhat unusual request. Most people asking about OLE imbedded images in Access are asking about how to convert them from OLE objects into raw binary data, not the other way around. Current versions of Access have features like the Image control that can display bitmap images without having to deal with the complications of OLE "wrappers" being added to the object data.
Still, here is one way to do what you requested. It uses an Access.Application object, so Access must be installed on the machine for this to work. It also requires a Form inside the Access database where
the form itself is bound to the table containing the OLE image field you want to insert,
the only control on the form is a Bound Object Frame, bound to the OLE field.
The sample code also assumes that the table being updated has a numeric primary key field named [ID].
private void button1_Click(object sender, EventArgs e)
{
// test data
int recordIdToUpdate = 15;
string bmpPath = #"C:\Users\Gord\Pictures\bmpMe.bmp";
var paths = new System.Collections.Specialized.StringCollection();
paths.Add(bmpPath);
Clipboard.SetFileDropList(paths);
// COM Reference required:
// Microsoft Access 14.0 Object Library
var accApp = new Microsoft.Office.Interop.Access.Application();
accApp.OpenCurrentDatabase(#"C:\Users\Public\Database1.accdb");
accApp.DoCmd.OpenForm(
"PhotoForm",
Microsoft.Office.Interop.Access.AcFormView.acNormal,
null,
"ID=" + recordIdToUpdate);
accApp.DoCmd.RunCommand(Microsoft.Office.Interop.Access.AcCommand.acCmdPaste);
accApp.DoCmd.Close(
Microsoft.Office.Interop.Access.AcObjectType.acForm,
"PhotoForm",
Microsoft.Office.Interop.Access.AcCloseSave.acSaveNo);
accApp.CloseCurrentDatabase();
accApp.Quit();
this.Close();
}
private string ImageToBase64String(Image image)
{
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, image.RawFormat);
return Convert.ToBase64String(stream.ToArray());
}
}
private void SaveButton()
{
string Pic = ImageToBase64String(PicBox.Image);
OleDbCommand PicSave = new OleDbCommand("INSERT INTO Picture(ID,PICTURE)VALUES(" + PicId.Text + ",'" + Pic + "')", con);
con.Open();
var SaveValue = PicSave.ExecuteNonQuery();
if (SaveValue > 0)
{
MessageBox.Show("Record Saved", "Information");
ValueClear();
}
else
MessageBox.Show("Rocord Not Saved", "Erro Msg");
con.Close();
}

Populating a Combo Box

I created a Windows Form, with a ComboBox, and a Local Database in Visual Studio 2010. The database has a table with a column whose rows I want to list in the combo box. How can I achieve this?
I tried adding a data source with the column I am interested in through the IDE, but it did not work.
I created a Windows Forms Application with a Windows Form containing a ComboBox.
I created a Local Database containing a Table with a single column and three test rows.
I added a data source containing the column I am interested in.
Finally, I bound the combo box to the data source, but the result is strange.
This is the raw code to accomplish what you are asking:
string strCmd = "";
string strConn = "";
SqlConnection sqlConn = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand(strCmd, sqlConn);
SqlDataReader sqlRdr = new SqlDataReader();
sqlConn.Open();
if (comboBox1.Items.Count > 0)
comboBox1.Items.Clear();
sqlRdr = sqlCmd.ExecuteReader();
while (sqlRdr.Read())
comboBox1.Items.Add(sqlRdr[0].ToString());
sqlRdr.Close();
sqlConn.Close();
There are a few things you will need to wire-up first though. The first one is this:
string strCmd = ""; // Insert your SQL statement here.
Second:
string strConn = ""; // Your db connection string goes here.
Thirdly:
if (comboBox1.Items.Count > 0) // You don't have to use this. It just checks to see
comboBox1.Items.Clear(); // if there is anything in the combobox and clears it.
Lastly, since you are making something that handles interactions between your form and a database, I strongly suggest that you use SqlParameters to prevent SQL Injection attacks.

How to populate listbox from excel using C#

I have an windows application. I browse for the file and select the excel file using OpenFileDialog control. The excel file contains email id's in column A. I want to populate the list-box with excel file column values. Office 2003 is installed on my machine. Can somebody Please help me out?
Thanks in Advance.
Refer: Reading Excel files from C#
To connect to an excel file you need the appropriate connection string:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=<YourExcelPath>;
Extended Properties=\"Excel 12.0;HDR=YES;\"";
After use the OleDb classes to query the information from the file:
string selectCmd = "SELECT * FROM <SheetName>";
using(OleDbConnection excelConn = new OleDbConnection(connString))
{
excelConn.Open();
OleDbCommand command = new OleDbCommand(selectCmd, excelConn);
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable sheetInfo = new DataTable();
dataAdapter.Fill(sheetInfo);
//Do something with the data.
Bind your control with this datatable here
}
So you need to replace "YourExcelPath" with the path of your excel file..

To open new Excel sheet from Silverlight

I creating Silverlight App, while exporting grid into excel, I need to open a new Excel sheet but I was not able to open a new Excel within silverlight. I am using Telerik controls, in their examples , they are saving a new excel and then exoporting data. But my client need not want the save operation performed before exporting the Grid data.
The flow should be like the one below:
1. Open new excel (Excel should be in front of the screen)
2. export data
3. Saving the excel is enduser 's choice .
The end user may or may not save the Excel sheet according to their need.
Can any one help me to solve this problem.
Thank You
private void button8_Click(object sender, RoutedEventArgs e)
{
dynamic excelApp;
excelApp = AutomationFactory.CreateObject("Excel.Application");
excelApp.Visible = true;
dynamic workbook = excelApp.workbooks;
workbook.Add();
dynamic sheet = excelApp.ActiveSheet;
dynamic cell = null;
int index = 1;
foreach (unite emp in dataGrid1.ItemsSource)
{
cell = sheet.Cells[index, 1];
cell.Value = emp.unite_description;
cell = sheet.Cells[index, 2];
//cell.Value = emp.EmployeeId;
//cell = sheet.Cells[index, 3];
//cell.Value = emp.Department;
index++;
}
}
This is what I found when I had the same problem as you and it's working as you asked. (Declaring variables as dynamic is probably not necessary)
Use excellite library. it is an appropriate free tool for reading and writing Excel files.
you can find it hear: http://excellite.codeplex.com/

Resources