Importing data from Excel to database using asp.net - c#

I want to import data from Excel to database using asp.net. I'm using VS-2012 to do this.
This is my code for the click event. But when I upload the file and click on the button the page shows "Page not found" error.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("select * from [Sheet$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
OleDbcon.Open();
DbDataReader dr = cmd.ExecuteReader();
string con_str = "Gems1ConnectionString1";
SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
bulkInsert.DestinationTableName = "tbl_energy_report";
bulkInsert.WriteToServer(dr);
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
Label1.ForeColor = Color.Green;
Label1.Text = "Succefully Imported the File";
}
else
{
Label1.ForeColor = Color.Red;
Label1.Text = "Please Select A File";
}
}
Please help.

on the first line try to assign the full path manually without using fileupload and with local path like:
string path = #"C:\fileName.xls";
and see if it works!

Related

Import Excel File to DataGridView then Update DataGridView to DataBase (Using C# and Visual Studio)

See Image Click Here
I can currently update it to the grid view successfully.
But I dont know how to save it to the database yet.
This is the code I used for excel to datagridview
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
string PathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [Sheet1$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
the name of my dataset: caDataSet
the name of my bindingsource: clBindingSource
the name of my tableadapter: clTableAdapter
the name of my database: ca.mdf
the name of my table in database: cl
variables in table include: custno, bcust,name,addr,ket,......,client

How do I connect a MS Access database with a password and a .mdb , accdb database

I want to connect different access database (they have same tables, same columns) to my system to make a report and this database has a password. I use a openfileDialog to take this database from my files and I want to connect both .mdb, .accdb but but when I use Microsoft.jet.oledb.12.0, I get an error
The microsoft.jet.olebd.12.0 provider is not registered on local machine
This is my code:
private void tileBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open file Dialog";
fdlg.InitialDirectory = #"C:\Desktop";
fdlg.Filter = "(*.mdb)|*.mdb|(*.accdb)|*accdb";
//fdlg.Filter = "All Files (*.*)|*.mdb|*.accdb" + "MS-Access Database Files (*.accdb)|*.accdb, (*.mdb)|*.mdb";
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = fdlg.FileName;
}
}
private void txtRead_Click(object sender, EventArgs e)
{
//connection string
String strDSN = "Provider=Microsoft.Jet.OLEDB.12.0;" + "Data Source=" + txtFilePath.Text;
try
{
//Create a connection and open it
OleDbConnection conn = new OleDbConnection(strDSN);
conn.Open();
String strSQl = "SELECT * FROM Student;";
//create data adapter
OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQl, conn);
// Create and fill dataset
DataSet dtSet = new DataSet();
myCmd.Fill(dtSet);
DataTable dt = dtSet.Tables[0];
dataGridView1.DataSource = dtSet.Tables[0];
//add items to the list box
listBox1.Items.Add("ID,F_Name,S_Name," + "Age");
listBox1.Items.Add("=====================================");
foreach (DataColumn dc in dt.Columns)
{
listBox1.Items.Add(dc.ColumnName + "," + dc.DataType + "," + dc.Unique + "," + dc.AutoIncrement + "," + dc.AllowDBNull);
}
OleDbCommand cmd = new OleDbCommand("SELECT student.ID, student.F_name, student.S_name, student.Age, Teachers_Info.Teachers_ID, Teachers_Info.Firstname, Teachers_Info.Surname, Teachers_Info.Teachers_Subject, Teachers_Info.Teachers_code FROM student, Teachers_Info ORDER BY student.ID;", conn);
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
txtID.Text = (Reader["ID"].ToString());
txtF_name.Text = (Reader["F_name"].ToString());
txtS_name.Text = (Reader["S_name"].ToString());
txtAge.Text = (Reader["Age"].ToString());
txtTeachers_ID.Text = (Reader["Teachers_ID"].ToString());
txtFirstname.Text = (Reader["Firstname"].ToString());
txtSurname.Text = (Reader["Surname"].ToString());
txtTeachers_Subject.Text = (Reader["Teachers_Subject"].ToString());
txtTeachers_code.Text = (Reader["Teachers_code"].ToString());
}
//close connection
conn.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message.ToString());
}
}

how to Upload a excel file to sql database table using c# windows form application

I want to upload a excel file through windows form application in c# and want to import the data to database ( Mysql server). how can i do that??? I have created a form which requires me to upload a excel file into the mysql database . its an bulk insert data to database table.
My Excel File Contain columns like userid,password,first_name,last_name,user_group AND
MySql Database table(aster_users) Contain many columns like userid,password,first_name,last_name,user_group,queue,active,created_date,created_by,role ..
i need to upload that excel file to my database and other columns will get empty or null that's not a matter.
My Form design is
Here is My c# Code:
using MySql.Data.MySqlClient;
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace UploadFileToDatabase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String MyConString = "SERVER=******;" +
"DATABASE=dbs;" +
"UID=root;" +
"PASSWORD=pwsd;" + "Convert Zero Datetime = True";
private void BtnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text files | *.csv";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName;
fileName = dlg.FileName;
txtfilepath.Text = fileName;
}
}
private void btnUpload_Click(object sender, EventArgs e)
{
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtfileparth.Text + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
string sqlConnectionString = MyConString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.ColumnMappings.Add("[userid]", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.DestinationTableName = "aster_users";
bulkCopy.WriteToServer(dr);
MessageBox.Show("Upload Successfull!");
}
}
}
}
Here is how i tried.i got an error message like this
Additional information: External table is not in the expected format.
in this line connection.Open(); . How can this be Done?
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace IMPORT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String MyConString = "SERVER=******;" +
"DATABASE=db;" +
"UID=root;" +
"PASSWORD=pws;";
private void btnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
openfiledialog1.ShowDialog();
openfiledialog1.Filter = "allfiles|*.xls";
txtfilepath.Text = openfiledialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
string path = txtfilepath.Text;
string ConnString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties = Excel 8.0";
DataTable Data = new DataTable();
using (OleDbConnection conn =new OleDbConnection(ConnString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"SELECT * FROM [dataGridView1_Data$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
string ConnStr = MyConString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr))
{
bulkCopy.DestinationTableName = "TABLE NAME";
bulkCopy.ColumnMappings.Add("userid", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.WriteToServer(Data);
MessageBox.Show("UPLOAD SUCCESSFULLY");
}
}
}
An example found http://technico.qnownow.com/bulk-copy-data-from-excel-to-destination-db-using-sql-bulk-copy/.
And
ERROR: Additional information: External table is not in the expected format
ஆர்த்தி,
Use the Below Connection String Format
string File = sResponsedExcelFilePath;
string result = Path.GetFileName(sFilePath);
ExcelReaderConnString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + File +"\\"+ result + ";Extended Properties=Excel 12.0;");
Hope this works for you.
There is an awesome link that shows how to upload to c# datatable from excel...in case the link dies I am sharing the procedure....
The excel Connection Strings for diff versions:
private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
The File select event:
private void BtnSelectFile_Click(object sender, EventArgs e)
{
DataTable dt;
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Excel files | *.xls";
if (dlg.ShowDialog() == DialogResult.OK)
{
string filePath = dlg.FileName;
string extension = Path.GetExtension(filePath);
string conStr, sheetName;
conStr = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03
conStr = string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07 to later
conStr = string.Format(Excel07ConString, filePath);
break;
}
//Read Data from the Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
dt = new DataTable();
cmd.CommandText = "SELECT * From [Sheet1$]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
}
}
}
//Save the datatable to Database
string sqlConnectionString = MyConString;
if(dt != null)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.ColumnMappings.Add("[userid]", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.DestinationTableName = "aster_users";
bulkCopy.WriteToServer(dt);
MessageBox.Show("Upload Successfull!");
}
}
}
}
Then you can just save the datatable to mySql database which I hope you know how to do...If you can't then comment I'll try my best to help you. Thank You
Hope this helps....
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace IMPORT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String MyConString = "SERVER=******;" +
"DATABASE=db;" +
"UID=root;" +
"PASSWORD=pws;";
private void btnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
openfiledialog1.ShowDialog();
openfiledialog1.Filter = "allfiles|*.xls";
txtfilepath.Text = openfiledialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
string path = txtfilepath.Text;
string ConnString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties = Excel 8.0";
DataTable Data = new DataTable();
using (OleDbConnection conn =new OleDbConnection(ConnString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"SELECT * FROM [dataGridView1_Data$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
string ConnStr = MyConString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr))
{
bulkCopy.DestinationTableName = "TABLE NAME";
bulkCopy.ColumnMappings.Add("userid", "userid");
bulkCopy.ColumnMappings.Add("password", "password");
bulkCopy.ColumnMappings.Add("first_name", "first_name");
bulkCopy.ColumnMappings.Add("last_name", "last_name");
bulkCopy.ColumnMappings.Add("user_group", "user_group");
bulkCopy.WriteToServer(Data);
MessageBox.Show("UPLOAD SUCCESSFULLY");
}
}
}
I had huge problems trying to use either/both Jet and ACE.OLEDB providers. You could try this o/s library ClosedXML, which will import xlsx files: 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
Available via Nuget. It has its own wiki: https://github.com/ClosedXML/ClosedXML/wiki

OleDbException was unhandled; System resource exceeded

public void LoadExcel_Click(object sender, EventArgs e)
{
OpenFileDialog fileDLG = new OpenFileDialog();
fileDLG.Title = "Open Excel File";
fileDLG.Filter = "Excel Files|*.xls;*.xlsx";
fileDLG.InitialDirectory = #"C:\Users\...\Desktop\";
if (fileDLG.ShowDialog() == DialogResult.OK)
{
string filename = System.IO.Path.GetFileName(fileDLG.FileName);
string path = System.IO.Path.GetDirectoryName(fileDLG.FileName);
excelLocationTB.Text = #path + "\\" + filename;
string ExcelFile = #excelLocationTB.Text;
if (!File.Exists(ExcelFile))
MessageBox.Show(String.Format("File {0} does not Exist", ExcelFile));
OleDbConnection theConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";Extended Properties=Excel 12.0;");
theConnection.Open();
OleDbDataAdapter theDataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", theConnection);
DataSet DS = new DataSet();
theDataAdapter.Fill(DS, "ExcelInfo");
dataGridView1.DataSource = DS.Tables["ExcelInfo"];
formatDataGrid();
MessageBox.Show("Excel File Loaded");
toolStripProgressBar1.Value += 0;
}
}
Ok so I got this code off of Microsoft.
theDataAdapter.Fill(DS, "ExcelInfo");
This is the line that gave me the error.
Basically this code is supposed to use a dialog box to open the file and display it on the form. Whenever I opened an Excel file, it would give me this error. I even tried creating a blank excel file and it still gave me this.
Modified your code. added OleDbCommand to do the query selection. just try.
OleDbConnection theConnection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Projects\Demo\Demo.xls;Extended Properties=Excel 8.0;");
theConnection.Open();
OleDbCommand theCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", theConnection);
OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(theCmd);
DataSet DS = new DataSet();
theDataAdapter.Fill(DS);
theConnection.Close();
I have seen this error before and it might not have anything to do with your code. The code below works fine, but if you are getting your source that has blocked the file, make sure you right-click the file and go to properties and check unblock. This could be if you are downloading the file from some source etc. A good test is to just open the exported excel file and save it and try again. Or copy the contents into a new excel file.
Again the code below works fine, but when I tried to import without unblocking or going into the file and saving it I was getting the same error. The error message is deceiving.
string excelconString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1""", filePath);
string excelQuery = "select col1 from [Sheet1$]";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
using (var excelConn = new OleDbConnection(excelconString))
{
excelConn.Open();
using (var oda = new OleDbDataAdapter(excelQuery, excelConn))
{
oda.Fill(ds);
dt = ds.Tables[0];
}
}

Reading a spreadsheetl file from fileupload control into filestream

I am trying to find the best way of selecting an excel spreadsheet (xls and xlsx) using a fileupload control and then parsing it with filestream object and then populating a dataset.
This is my code so far which does the job but how it differs is I am saving the excel spreadsheet to a folder in my solution then querying the data using Microsoft ACE OLEDB connection.
protected void btnUpload_Click(object sender, EventArgs e)
{
string connectingString = "";
if (ctrlFileUpload.HasFile)
{
string fileName =
Path.GetFileName(ctrlFileUpload.PostedFile.FileName);
string fileExtension =
Path.GetExtension(ctrlFileUpload.PostedFile.FileName);
//Path.GetExtension(ctrlFileUpload.PostedFile.ContentType);
string fileLocation =
Server.MapPath("~/App_Data/" + fileName);
ctrlFileUpload.SaveAs(fileLocation);
// Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectingString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
}
// Create OleDb Connection and OleD Command
using (OleDbConnection con = new OleDbConnection(connectingString))
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
//DataTable dtExcelRecords = new DataTable();
DataSet ds = new DataSet();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "Select * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
//dAdapter.Fill(dtExcelRecords);
dAdapter.Fill(ds);
//GridView1.DataSource = dtExcelRecords;
//GridView1.DataBind();
}
catch (Exception ex)
{
}
}
}
}
So to summarise I want to read the data in a spreadsheet and then bind it to a dataset but without saving the file to a physical path.
Is there a cleaner way of writing this code that I am missing. Thanks!!
I think it not possible to get data without save file to your server
If you can't save uploded file how can you give Data Source to your oleDbConnection string ??
you can delete file after finish this execution if you don't want to keep the file.
you can also refer this way https://stackoverflow.com/a/12420416/284240

Categories

Resources