Excel c#.net retrieving data without opening excel in the background - c#

I am trying to read a data in an excel sheet using C#, here is my code.
public void ReadExcel()
{
try
{
string sheetName = "Sheet1$A1:C6";
DataTable sheetTable = loadSingleSheet(#"C:\Users\..\Desktop\Sample.xls", sheetName);
}
catch (Exception e)
{
throw e;
}
}
private OleDbConnection returnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
private DataTable loadSingleSheet(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = this.returnConnection(fileName))
{
conn.Open();
// retrieve the data using data adapter
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
sheetAdapter.Fill(sheetData);
}
return sheetData;
}
But DataTable always get null value

Here it is how to do it using ODBC and ADO.Net
private void Form1_Load(object sender, EventArgs e)
{
try
{
string sheetName = "Sheet1$";// Read the whole excel sheet document
DataTable sheetTable = loadSingleSheet(#"C:\excelFile.xls", sheetName);
dataGridView1.DataSource = sheetTable;
string sheetNameWithRange = "Sheet1$A1:D10"; // Read excel sheet document from A1 cell to D10 cell values.
DataTable sheetTableWithRange = loadSingleSheet(#"C:\excelFile.xls",sheetNameWithRange);
dataGridView2.DataSource = sheetTableWithRange;
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "");
}
}
private OleDbConnection returnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
private DataTable loadSingleSheet(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = this.returnConnection(fileName))
{
conn.Open();
// retrieve the data using data adapter
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
sheetAdapter.Fill(sheetData);
}
return sheetData;
}

Related

C# Method to Load Excel File to DataTable or DateSet

good afternoon,
I am trying to create a method that returns the data of an excel file to call it through a FileDialog for example ... Here is my code:
public static DataSet MtdGetExcel(string prtlocalFile)
{
string sDBstrExcel = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=0\"", prtlocalFile);
OleDbConnection conexaoExcel = new OleDbConnection(sDBstrExcel);
conexaoExcel.Open();
DataTable dt = conexaoExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataSet output = new DataSet();
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString(); //Obtém o nome da planilha corrente
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conexaoExcel); //Obtém todas linhas da planilha corrente
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet); //Copia os dados da planilha para o DataTable
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
conexaoExcel.Close();
return output;
}
But when I call the method does not return anything in the DataGridView...
public void testeImportExcel()
{
try
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Selecione o relatório do Detran";
fdlg.InitialDirectory = #"c:\";
//string endereco = fdlg.FileName;
//txtNomeArquivo.Text = fdlg.FileName;
fdlg.Filter = "Excel File (*.xlsx)|*.xlsx";
//fdlg.Filter = "Excel File (*.csv)|*.csv";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
myDtGridView.DataSource = MtdGetExcel(fdlg.FileName);
myDtGridView.AutoGenerateColumns = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Result:
Can you help me?
Here is my exact method that I have in production:
public DataTable ReadExcel(string fileName, string TableName)
{
DataTable dt = new DataTable();
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0\"");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + TableName, conn);
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (!reader.IsClosed)
{
dt.Load(reader);
}
}
finally
{
conn.Close();
}
return dt;
}
I'm sure just by looking at it you can tell- this method takes in the fileName (or file path) of the Excel you're wanting to read from. Creates the connection string and command. Excel will be read like a database and its worksheets will be read like tables. TableName is the name of the worksheet (table). This method returns a DataTable that can be added to a DataSet if needed.

How to save my data from excel which auto generate gridview columns?

I know this might be a repeated question but I couldn't find it anywhere.
I am importing data from excel to gridview but how do I save the gridview data into database and the column from the gridview are auto generated.
The data is already reflected in the gridview how do i save it in the database?
It would be better if anyone can teach me how to insert directly from excel to database without using gridview as the medium.(tried using this but kept telling me that the excel sheet does not exist).
code to bind grid view:
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
.ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
.ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, isHDR);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
//Bind Data to GridView
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
Yes I am using code from aspsnippets.
I recently done this, but i only did it for fileType Microsoft Office Excel Worksheet (.xlsx) . At first you have to copy the excel file to your Application directory, Then you save the data to DataTable and finally bind it to Gridview.
Use these namespaces
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
Here is the method
private void Import_To_GridTest(string FilePath)
{
DataTable dt =new DataTable();
try
{
string sSheetName = null;
string sConnection = null;
DataTable dtTablesList = default(DataTable);
OleDbDataAdapter oda = new OleDbDataAdapter();
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=YES;IMEX=1\"";
sConnection = String.Format(sConnection, FilePath);
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();
dtTablesList = oleExcelConnection.GetSchema("Tables");
if (dtTablesList.Rows.Count > 0)
{
sSheetName = dtTablesList.Rows[0]["TABLE_NAME"].ToString();
}
dtTablesList.Clear();
dtTablesList.Dispose();
if (!string.IsNullOrEmpty(sSheetName))
{
var oleExcelCommand = oleExcelConnection.CreateCommand();
oleExcelCommand.CommandText = "Select * From [" + sSheetName + "]";
oleExcelCommand.CommandType = CommandType.Text;
oda.SelectCommand = oleExcelCommand;
oda.Fill(dt);
oleExcelConnection.Close();
}
oleExcelConnection.Close();
gridview1.DataSource = dt;
gridview1.DataBind();
}
catch (Exception e)
{
lblMsg.Text = "Unspecified Error Occured..!! <br>" + e.Message;
divMsg.Attributes["class"] = "alert alert-danger";
mainDiv.Visible = true;
File.Delete(FilePath);
}
}
Finally the Submit button Click event
protected void btnsubmit_OnClick(object sender, EventArgs e)
{
if (fileUpload1.HasFiles)
{
string FileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
string FolderPath = "Excels/"; // your path
string FilePath = Server.MapPath(FolderPath + DateTime.Now.ToString("ddmmyyhhmmss") + FileName);
// copy and save the the excel
fileUpload1.SaveAs(FilePath);
Import_To_GridTest(FilePath);
}
}
Update : For saving data to database Use SqlBulkCopy Class
private void SqlbulkCopy(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string consString = ConfigurationManager.ConnectionStrings["Bulkcopy"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.leads";
//[OPTIONAL]: Map the DataTable columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Currunt_Company", "CuCompany");
sqlBulkCopy.ColumnMappings.Add("Currunt_Product", "CuProduct");
sqlBulkCopy.ColumnMappings.Add("Quantity", "Quantity");
sqlBulkCopy.ColumnMappings.Add("Unit_Price", "UnitPrice");
sqlBulkCopy.ColumnMappings.Add("Total_Price", "TotalPrice");
sqlBulkCopy.ColumnMappings.Add("Contect_Person", "ContectPerson");
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
}

c# OleDbDataAdapter excel missing last row

GetExcelSheetNames:
static String[] GetExcelSheetNames(string excelFile, string extention)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string filepath= excelFile;// +; excelFile;
string Conn = "";
if (extention == "xls")
Conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath+ ";Extended Properties=Excel 8.0;";
else Conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath+ ";Extended Properties=Excel 12.0";
try
{
// Connection String. Change the excel file to the file you
// will search.
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(Conn);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] 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++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
GetTable:
private DataSet GetTable(string filepath, string extention)
{
string strConn;
if (extention == "xls")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
}
else
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0";
}
DataSet myDataSet = new DataSet();
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [" + GetExcelSheetNames(filepath, extention)[0] + "]", strConn);
myCommand.Fill(myDataSet, "ExcelInfo");
if (myDataSet.Tables[0].Rows.Count > 0)
{
return myDataSet;
}
else return null;
}
I export excel data to datatable by using OleDbDataAdapter.
My both method (above side) works however last row is missing .
Where i miss exactly how can i get all rows from excel ?
Any help will be appreciated.
Thanks.

Bind data from excel sheet to repeater or GridView

What is efficient & simplest way to bind data from excel sheet to repeater or GridView.
I think it is easy to create OleDbDataAdapter and creating a DataSet will do the job.
You can easily bind a DataSet to gridview
eg
var conn = ("Provider=Microsoft.Jet.OLEDB.4.0;" +
("Data Source=add file path here;" +
"Extended Properties=\"Excel 8.0;\""));
var query = "SELECT table from [sheet1$]";
var adpterObj = new OleDbDataAdapter(SSQL, conn);
var ds = new DataSet();
adpterObj.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
You should read data from Excel using any one library (OLEDB Connection, COM Object or any other) and after Puts result to any .Net objects (DataSet, DataTable) according to your requirement. then bind DataSet to your Repeater.
maybe this link will solve your problem
click me
public static DataSet ImportExcelXLS(string FileName, bool hasHeaders) {
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn)) {
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(
OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow schemaRow in schemaTable.Rows) {
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_")) {
try {
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
} catch (Exception ex) {
throw new Exception(ex.Message + string.Format("Sheet:{0}.File:F{1}", sheet, FileName), ex);
}
}
}
}
return output;
}
First we have to browse
void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Excel files (*.xls)|*.xls";
fileDialog.InitialDirectory = "C:";
fileDialog.Title = "Select a Excel file";
if (fileDialog.ShowDialog() == DialogResult.OK)
txtMsg.Text = fileDialog.FileName;
if (string.IsNullOrEmpty(txtMsg.Text))
return;
}
Note: txtMsg.Text = fileDialog.FileName; //here file name keeping in one text box
Then we can upload excel sheet to gridview...
private void btnUpload_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtMsg.Text))
{
InsertBuyBackExceldata(txtMsg.Text);
}
}
Here we can call InsertBuyBackExceldata method
void InsertBuyBackExceldata(string filePath)
{
if (buyBackServiceProxyController == null)
buyBackServiceProxyController = new ProxyController();
buyBackServiceServiceProxy = buyBackServiceProxyController.GetProxy();
ListBuyBackrequest = new List();
String[] a= GetExcelSheetNames(filePath); // This method for get sheet names
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", filePath);
//string a=filePath.
String sheetName = a[0];
var adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, sheetName );
DataTable data = ds.Tables[sheetName ];
BindGrid(data);
}
here I am calling a method to get Sheet name.
private String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
//Excel Uploading to Gridview
void BindGrid(DataTable Data)
{
try
{
// Adding one check box
DataGridViewCheckBoxColumn chkSelection = new DataGridViewCheckBoxColumn();
chkSelection.Name = "Selection";
dgItemsForBuyBackGrid.Columns.Add(chkSelection);
int intCount = Data.Rows.Count;
if (i==true)
{
if (intCount > 0)
{
ExcelGrid.DataSource = Data;
ExcelGrid.BindPage();
}
else
{
ExcelGrid.DataSource = null;
ExcelGrid.BindPage();
return;
}
// Here I am setting Grid colomns properties this name should equal to Excel //column names.
ExcelGrid.Columns["BI"].ReadOnly = true;
ExcelGrid.Columns["AAA"].ReadOnly = true;
ExcelGrid.Columns["AAB"].ReadOnly = true;
ExcelGrid.Columns["AAC"].ReadOnly = true;
ExcelGrid.Columns["AAD"].ReadOnly = true;
ExcelGrid.Columns["AAE"].ReadOnly = true;
ExcelGrid.Columns["AAF"].ReadOnly = true;
ExcelGrid.Columns["AAG"].ReadOnly = false;
}
else
{
// Some Code
}
}
catch (Exception ex)
{
}
}
}
}
Excel 2007 and other versions Uploading to Gridview in .Net.
Steps:
1) AccessDatabaseEngine.exe --> (Install)
And some code changes from above code.
2) Browse Click
private void btnBrowse_Click(object sender, EventArgs e)
{
-------
fileDialog.Filter ="Excel files (*.xls;*xlsx;*xlsb)|*.xls;*xlsx;*xlsb";
// Show those extentional files.
--------------
}
3) Process Click
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";
Thank You :)

how to import multiple excel sheets into 2 sql server tables?

Am having one excel file with 2 different worksheets as fundmodelrate and project.Now I want to import these 2 different sheet values into 2 different sql tables(k2_fundmodelrate,k2_project).I can able to do import only if am working with 1 sheet and and 1 table,but I want two sheets values to be imported on two tables at the same time on button click event.
My code below:
private String strConnection = "Data Source=kuws4;Initial Catalog=jes;User ID=sa;Password=******";
protected void btnSend_Click(object sender, EventArgs e)
{
string path = fileuploadExcel.PostedFile.FileName;
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\fmr.xls;Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select * from [FundModelRate$]", excelConnection);
//OleDbCommand cmd1 = new OleDbCommand("Select * from [FundModelRate$], [Project$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "K2_FundModelRate";
// sqlBulk.DestinationTableName = "K2_Project";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
I think the only way is to loop through your two sheets.
Have a look at This post. This will help you get the sheet names.
When you have the sheet names, you can then just loop through them and then load them into SQL.
Maybe this can help you:
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string excelConnection = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
excelConnection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
excelConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
objConn = new OleDbConnection(excelConnection);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
for(int j=0; j < excelSheets.Length; j++)
{
OleDbCommand cmd = new OleDbCommand("Select * from " + excelSheets[j], excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "YourDestinationTableName";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
Note: Not tested
public void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "test_data";//sql table name
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if havedifferent
string myexceldataquery = "select * from [Sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath + ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string ssqlconnectionstring = "server=ServerName;user id=sa;password=sa;database=Databasename;connection reset=false";
//execute a query to erase any previous data from our destination table
string sclearsql = "Delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
DataTable dt = new DataTable();
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
oledbconn.Close();
}
catch (Exception)
{
throw;
}
}
/*---------- call that file on buttonclick through OpenDialogBox--------*/
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
string strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
importdatafromexcel(strfilename);
}
Console.WriteLine(result);
MessageBox.Show("Exported to SQL successfully");
}

Categories