Excel Tool to Import and Export data from (and to) Excel File
This small Application is really help to those who were in the need to get data from excel file and export to excel file
This is the screen shot of the application.
It have 3 buttons
Browse
Generate
Export to Excel
Browse
When user clicks on browse button one popup window will open it gets the filename along with path.
This is the code for browse button click
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Excel file only";
ofd.CheckFileExists = false;
ofd.CheckPathExists = true;
ofd.AddExtension = true;
ofd.DefaultExt = "txt";
ofd.ShowReadOnly = true;
ofd.ShowHelp = true;
if (ofd.ShowDialog() == DialogResult.Cancel)
Application.Exit();
strfile = ofd.FileName.ToString();
}
Name and path of the file will be saved in strfile.
Generate Button
Generate Button will connect to the specified file and fill the grid with the excel file content.
coding for Generate Button click
private void button1_Click(object sender, EventArgs e)
{
DataSet objDataset1 = new DataSet();
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strfile + ";Extended Properties=Excel 5.0";
OleDbConnection objConn = new OleDbConnection(ConnectionString);
objConn.Open();
String strConString = "SELECT * from [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataTable dt = new DataTable();
objAdapter1.Fill(objDataset1, "ExcelData");
dataGridView1.DataSource = objDataset1.Tables[0];
objConn.Close();
}
( Note check with query if your excel file does have sheet1 means just replace sheet1 to your sheet name.)
Export To Excel
Export to Excel button will export the content of grid to excel.
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
exportToExcel(dt, "c:\\Exportedtoexcel.xls");
MessageBox.Show("Exported to Excel successfully");
}
>Download the tool
No comments:
Post a Comment