I've imported an Excel file and displayed the data using a datagrid view, but I want also to save in to my MS Access database.
Can it be done with OleDbCommand and select * into ?
Below is the code for my import from an Excel file; for the import I created it based on another post here:
private void BtnImport1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
openfile1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm";
openfile1.Title = "Seleccione el archivo de Excel";
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openfile1.FileName.Equals("") == false)
{
this.tBox1.Text = openfile1.FileName;
Ruta = openfile1.FileName;
}
}
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Ruta + ";Extended Properties = \"Excel 12.0; HDR=YES;\" ; ";
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * From [Hoja 1$]", con);
DataTable dt1Excel = new DataTable();
MyDataAdapter.Fill(dt1Excel);
dataGridView1.DataSource = dt1Excel;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Try it like this and feedback.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//here is a sample code which reads an Excel file Sheet1 which has 2 columns
//And inserts the same into an access table
//Change the file names, sheet name, table names and column names as per your requirements
//File Names, replae with your file names
string fileNameExcel = #"C:\your_path_here\Book1.xls";
string fileNameAccess = #"C:\your_path_here\Database1.mdb";
//Connection string for Excel
string connectionStringExcel =
string.Format("Data Source= {0};Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;", fileNameExcel);
//Connection string for Access
string ConnectionStringAccess =
string.Format("Data Source= {0}; Provider=Microsoft.Jet.OLEDB.4.0; Persist security Info = false", fileNameAccess);
//Connection object for Excel
OleDbConnection connExcel = new OleDbConnection(connectionStringExcel);
//Connection object for Access
OleDbConnection connAccess = new OleDbConnection(ConnectionStringAccess);
//Command object for Excel
OleDbCommand cmdExcel = connExcel.CreateCommand();
cmdExcel.CommandType = CommandType.Text;
cmdExcel.CommandText = "SELECT * FROM [Sheet1$]";
//Command object for Access
OleDbCommand cmdAccess = connAccess.CreateCommand();
cmdAccess.CommandType = CommandType.Text;
cmdAccess.CommandText = "INSERT INTO Table1 (Column1, Column2) VALUES(#column1, #column2)";
//Add parameter to Access command object
OleDbParameter param1 = new OleDbParameter("#column1", OleDbType.VarChar);
cmdAccess.Parameters.Add(param1);
OleDbParameter param2 = new OleDbParameter("#column2", OleDbType.VarChar);
cmdAccess.Parameters.Add(param2);
//Open connections
connExcel.Open();
connAccess.Open();
//Read Excel
OleDbDataReader drExcel = cmdExcel.ExecuteReader();
while (drExcel.Read())
{
//Assign values to access command parameters
param1.Value = drExcel[0].ToString();
param2.Value = drExcel[1].ToString();
//Insert values in access
cmdAccess.ExecuteNonQuery();
}
//close connections
connAccess.Close();
connExcel.Close();
}
}
}
Related
I am trying to show records in a DataGridView using Microsoft Access 2010. But the problem is each time i click on the button1 i get an error saying "The ConnectionString property has not been initialized"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Attendance_Generation_System
{
public partial class Take_attendance : Form
{
OleDbConnection conn = new OleDbConnection();
public Take_attendance()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
conn.ConnectionString=#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\UNI WORK\7th Semester\Visual Programming\Database31.accdb; " + "User id = admin; " + "Password = "; ;
OleDbCommand cmd =new OleDbCommand("SELECT * FROM Attendancerecord");
OleDbDataAdapter add = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
add.Fill(dt);
dataGridView1.DataSource=dt;
cmd.ExecuteNonQuery();
}
}
}
The error is clear that tells you the connection string is not assigned. So, you should assign the connection string for OleDbDataAdapter
var connectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\UNI WORK\7th Semester\Visual Programming\Database31.accdb; " + "User id = admin; " + "Password = ";
using (var oledbCnn = new OleDbConnection(connectionString))
{
oledbCnn.Open();
var cmd = new OleDbCommand("SELECT * FROM Attendancerecord", oledbCnn);
OleDbDataAdapter add = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
add.Fill(dt);
dataGridView1.DataSource = dt;
oledbCnn.Close();
}
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();
}
}
}
}
How to import the data from an Excel sheet into SQL Server database in asp net?
Dim OleDbcon As New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & path) + ";Extended Properties=Excel 12.0;")
Dim cmd As New OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon)
Dim objAdapter1 As New OleDbDataAdapter(cmd)
OleDbcon.Open()
Dim dr As DbDataReader = cmd.ExecuteReader()
Dim con_str As String = "Data Source=.;Initial Catalog=studentdetails;Integrated Security=True"
' Bulk Copy to SQL Server
Dim bulkInsert As New SqlBulkCopy(con_str)
bulkInsert.DestinationTableName = "Table name"
bulkInsert.WriteToServer(dr)
OleDbcon.Close()e here
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
we will create a method data table in which we will take excel sheet info in data table or data set after that we will push that data into SQL database table using SQL bulk
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
for()
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "customer1";
objbulk.ColumnMappings.Add("CustomerID", "CustomerID");
objbulk.ColumnMappings.Add("City", "City");
objbulk.ColumnMappings.Add("Country", "Country");
objbulk.ColumnMappings.Add("PostalCode", "PostalCode");
objbulk.WriteToServer(dt);
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected DataTable DataExcel()
{
DataTable dt = new System.Data.DataTable();
try
{
string filenname=#"C:\Users\sani singh\Documents\Excel03.xls";
string sWorkbook = "[Sheet1$]";
string ExcelConnectionString=#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source="+filenname+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection OleDbConn = new OleDbConnection(ExcelConnectionString);
OleDbConn.Open();
OleDbCommand OleDbCmd = new OleDbCommand(("SELECT * FROM " + sWorkbook),
OleDbConn);
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter(OleDbCmd);
sda.Fill(ds);
dt = ds.Tables[0];
OleDbConn.Close();
}
catch(Exception ex)
{
Response.Write(ex);
}
return dt;
}
}
}
Add a DataTable which can hold the Excel data generated via OLEDb.
string excelconnectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;Jet OLEDB:Max Buffer Size=256;");
using (OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring))
{
using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn))
{
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
dtBulkUpload.Load(dr);
}
}
Then serialize this DataTable to XML which can be sent to SQL Stored Proc. This approach is very useful if there are too many fields and you can send all in a single parameter
using (StringWriter strXML = new StringWriter())
{
dtBulkUpload.TableName = "BulkUpload";
dtBulkUpload.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false);
xmlString = strXML.ToString();
}
using (SqlCommand cmd = new SqlCommand("Stored PROC Name"))
{
cmd.Parameters.AddWithValue("#dtBulkUpload", bulkUploadData);
//SqlParameter returnParameter = cmd.Parameters.Add("#result", SqlDbType.NVarChar);
//returnParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#result", SqlDbType.NVarChar,3000);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
query = (string)(cmd.Parameters["#result"].Value.ToString());
con.Close();
I am trying to bind an EXCEL datasheet to a dataGridView? I think that this is close but I do not know why the data is not showing up in the grid. I have seen several post on Stackoverflow but I could not get any of them to work. So I decided to put my own example up and see if I can get someone to try this code. All the form needs is a button with the click event and the dataGridView.
Class Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Data.OleDb;
namespace TestExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
#"C:\Users\itpr13266\Desktop\test.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
}
}
You are missing dataGridView1.DataBind() after dataGridView1.DataSource = data;
Change your connection string Provider to the below given as , check in your excel file name is "test.xls" and sheet name is "Items" or not ?
String filenamewithpath = #"C:\Users\itpr13266\Desktop\test.xls";
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filenamewithpath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
here is the complete code.Works 100%
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String filenamewithpath = #"C:\Users\itpr13266\Desktop\test.xls";
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filenamewithpath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
I corrected the spelling mbd to mdb but now the error is
Micorsoft Jet database engine cannot find the input table or query employee make sure it exist and that its name is spelled correctly.
What I want to do is connect to database and extract four fields in the texbox here is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Empdetails
{
public partial class EGUI : Form
{
private OleDbConnection dbConn; // Connectionn object
private OleDbCommand dbCmd; // Command object
private OleDbDataReader dbReader;// Data Reader object
private Emp1 Edetails;
private string sConnection;
private string sql;
public EGUI()
{
InitializeComponent();
}
private void button1_Click(object sender,System.EventArgs e)
{
try
{
// Construct an object of the OleDbConnection
// class to store the connection string
// representing the type of data provider
// (database) and the source (actual db)
sConnection =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=employee.mdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
// Construct an object of the OleDbCommand
// class to hold the SQL query. Tie the
// OleDbCommand object to the OleDbConnection
// object
sql = "Select * From employee";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
// Create a dbReader object
dbReader = dbCmd.ExecuteReader();
while (dbReader.Read())
{
Edetails = new Emp1
(dbReader["Name"].ToString(), dbReader["Address"].ToString(), dbReader["SocialSecurityNumber"].ToString(), dbReader["Rate"].ToString());
textBox1.Text = dbReader["Name"].ToString();
textBox2.Text = dbReader["Address"].ToString();
textBox3.Text = dbReader["SocialSecurityNumber"].ToString();
textBox4.Text = dbReader["Rate"].ToString();
// tb1.Text = dbReader["FirstName"].ToString();
} // tb2.Text = dbReader["LastName"].ToString();
dbReader.Close();
dbConn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("exeption" + ex.ToString());
}
}
private void EGUI_Load(object sender, EventArgs e)
{
}
}
Tim and binil are right, you need to provide the full path. I tested your code and it works when you add the full path
try
{
// Construct an object of the OleDbConnection
// class to store the connection string
// representing the type of data provider
// (database) and the source (actual db)
string sConnection =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Code\\StackOverflowSamples\\ReadFromAccessDB\\employee.mdb";
using (OleDbConnection dbConn = new OleDbConnection(sConnection))
{
dbConn.Open();
// Construct an object of the OleDbCommand
// class to hold the SQL query. Tie the
// OleDbCommand object to the OleDbConnection
// object
string sql = "Select * From employee";
OleDbCommand dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
// Create a dbReader object
using (OleDbDataReader dbReader = dbCmd.ExecuteReader())
{
while (dbReader.Read())
{
Console.WriteLine(dbReader["EmployeeName"].ToString());
Console.WriteLine(dbReader["Address"].ToString());
Console.WriteLine(dbReader["SSN"].ToString());
Console.WriteLine(dbReader["Rate"].ToString());
}
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("exeption" + ex.ToString());
}
Console.ReadLine();
}
Do you need to provide the full path to the file in the connect string?