How to populate listbox from excel using C# - winforms

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..

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.

Data transfer using vb.net

I am new to vb.net and very confused at this point. I have experience with vba within excel and have taken a basic vb class at my university but I am clue less when it comes to this.
I have multi projects I would like to try, but I am stuck on how to transfer data, text string from one program to the other using a vb.net app!
I believe the process I am looking for is data binding? is that correct?
The 3 processes I am trying to accomplish.
Excel to Excel text or cell transfer/ copy and paste.
I have file A which is an excel file with rows and columns of data in cells. Then I have file B which is a template with graphs and some other formulas. I am trying to use a vb.net app to open file A copy all the data and paste into a sheet in file B. I have figured out how to open the files but as for the data transfer method I have not found anything.
Private Sub btn_Do_Click(sender As Object, e As EventArgs) Handles btn_Do.Click
Dim txtpath As String
Dim csvpath As String = "C:\Temp"
Dim FileTXT As String
Dim folderpath As String
Dim FinalFile As String
folderpath = "C:\Users\aholiday\Desktop\Data Dump"
FileTXT = cbo_FileList.Text
csvpath = "C:\Temp\" & FileTXT & ".csv"
txtpath = folderpath & "\" & FileTXT & ".txt"
FinalFile = "C:\Users\aholiday\Desktop\Book1"
File.Copy(txtpath, csvpath)
Process.Start("EXCEL.EXE", csvpath)
Process.Start("EXCEL.EXE", FinalFile)
File.Delete(csvpath)
End Sub
Access database to a chart in vb.net app.
Next I have an vb.net app that has a chart in it. How would I get data from an excel file into it. I have no code for this because I am not sure what the method I need is. I need this to be "live" meaning if someone changes something in the excel file it will update on the chart in the app. But the the first step is getting the data out of excel and into the chart. This is the only example I could find and its for Microsoft access as the data source. It didn't work.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)Handles Button1.Click
Chart1.Series.Add("Numbers")
Dim Conn As OleDbConnection = New OleDbConnection
Dim Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
Dim dataFile = "C:\Users\aholiday\Desktop\Database11.accdb"
Conn.ConnectionString = Provider & dataFile
Conn.Open()
'Adds data to chart
Dim cmd As OleDbCommand = New OleDbCommand("Select [Month],[Number] FROM [Table1]", Conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
Chart1.Series("Table1").Points.AddXY(dr("Month").ToString, dr("Number").ToString)
End While
dr.Close()
cmd.Dispose()
End Sub
End Class
Excel to vb.net pictures and text string transfer.
And last. I have an vb.net app that have textbox and picture boxes in the design layout. I have an excel file with strings of text and pictures within cells. I would like code to copy the text and pictures and place them in the textbox and Picturebox.
I would like to learn how one would accomplish any of those.Please post any helpful content from sources. Any suggestions and especially examples would be awesome. Please nothing from Microsoft unless it crystal clear. I have spent about a day researching and googled everything I could think of and have found very little. None that work when I try to use it.
Thank you

Import excel file using c#.net [duplicate]

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.

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.

Pass password to excel file using vb script

i have a excel file it is password enabled in a script task i am reading the file using Vb
I am not able to pass the password so that it allows me to read from the file.
How can i do it.Where can i pass the password. I also tried using FileInfo class there is no option for that.
present script is:
Dim fs As FileStream
Dim sr As StreamReader
Dim line As String
fs = File.OpenRead(Dts.Variables("File_Name").Value)
sr = File.OpenText(Dts.Variables("File_Name").Value)
'Read first line of the file
line = sr.ReadLine
Dim str As String
str = line
sr.Close()
fs.Close()
It works if the file is not password enabled.Any help. Please
You could use the actual Excel COM Object Model.
There is a property of the Workbook class that allows you to set the password.

Resources