Application for importing Excel datasheet - c#

I Want to import a excel file and having trouble with the provider issue
Code are
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.IO;
using System.Data.SqlClient;
using System.Windows.Documents;
using System.Windows.Controls;
using ADOX;
namespace Import
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string SelectedTable = string.Empty;
private void button1_Click_1(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select file";
fdlg.InitialDirectory = #"c:\";
fdlg.FileName = txtFileName.Text;
fdlg.Filter = "Excel Sheet(*.xls)|*.xls|All Files(*.*)|*.*";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtFileName.Text = fdlg.FileName;
Import();
Application.DoEvents();
}
}
private void Import()
{
if (txtFileName.Text.Trim() != string.Empty)
{
try
{
string[] strTables = GetTableExcel(txtFileName.Text);
frmSelectTables objSelectTable = new frmSelectTables(strTables);
objSelectTable.ShowDialog(this);
objSelectTable.Dispose();
if ((SelectedTable != string.Empty) && (SelectedTable != null))
{
DataTable dt = GetDataTableExcel(txtFileName.Text, SelectedTable);
dataGridView1.DataSource = dt.DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
public static DataTable GetDataTableExcel(string strFileName, string Table)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + strFileName + "; Extended Properties = \"Excel 12.0;HDR=Yes;IMEX=1\";");
conn.Open();
string strQuery = "SELECT * FROM [" + Table + "]";
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
System.Data.DataSet ds = new System.Data.DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
public static string[] GetTableExcel(string strFileName)
{
string[] strTables = new string[100];
Catalog oCatlog = new Catalog();
ADOX.Table oTable = new ADOX.Table();
ADODB.Connection oConn = new ADODB.Connection();
oConn.Open("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + strFileName + "; Extended Properties = \"Excel 12.0;HDR=Yes;IMEX=1\";", "", "", 0);
oCatlog.ActiveConnection = oConn;
if (oCatlog.Tables.Count > 0)
{
int item = 0;
foreach (ADOX.Table tab in oCatlog.Tables)
{
if (tab.Type == "TABLE")
{
strTables[item] = tab.Name;
item++;
}
}
}
return strTables;
}
}
}
but the code gives Provider Can not be found,or not correctly installed
and improve the oledb connection version and Excel version in the code but thats not helping me to run the code.When I try to browse the excel file in the application i Got that error or exception

Is your operating system a 64 bit?
Do you a 64 bit installation of Microsoft Excel?
Have you installed the driver for 64 bit systems, which is available at:
http://www.microsoft.com/downloads/details.aspx?FamilyID=C06B8369-60DD-4B64-A44B-84B371EDE16D&displaylang=en

public void Form1_Load(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select file";
fdlg.InitialDirectory = #"d:\";
var txtFileName = fdlg.FileName;
fdlg.Filter = "Excel Sheet(*.xlsx)|*.xlsx|Excel Sheet(*.xls)|*.xls|All Files(*.*)|*.*";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtFileName = fdlg.FileName;
Import(txtFileName);
System.Windows.Forms.Application.DoEvents();
}
}
private void Import(string txtFileName)
{
if (txtFileName != string.Empty)
{
try
{
String name = "Sheet1"; // default Sheet1
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
txtFileName +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}

Related

System.ArgumentException: „Column does not belong to table .” - how to fix this error (import data from csv file to mysql database)?

In this case I'd like to import data from csv file to mysql database. For now i've written method which inserts that file:
1) Select file with extension "*.csv"
2) After select it loads data by dividing commas and continuing if are empty cells.
private DataTable ImportFile()
{
DataTable imported_data = new DataTable();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open csv file";
ofd.DefaultExt = "*.csv";
ofd.Filter = "Documents (*.csv)|*.csv";
ofd.ShowDialog();
FileInfo fi = new FileInfo(ofd.FileName);
string FileName1 = ofd.FileName;
string excel = fi.FullName;
using(StreamReader sr = new StreamReader(excel))
{
string header = sr.ReadLine();
if (string.IsNullOrEmpty(header))
{
MessageBox.Show("Not found or loaded not correct file.");
return null;
}
string[] header_columns = header.Split(',');
foreach(string header_column in header_columns)
{
imported_data.Columns.Add(header_column);
}
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (string.IsNullOrEmpty(linia)) continue;
string[] fields = line.Split(',');
DataRow imported_row = imported_data.NewRow();
for (int i = 0; i < fields.Count(); i++)
{
imported_row[i] = fields[i];
}
imported_data.Rows.Add(imported_row);
}
}
return imported_data;
}
Then the second method is when it has a connection with mysql database it inserts values to that database:
private void save_modules(DataTable imported_data)
{
string connection = "datasource=localhost;port=3306;username=root;password=";
using (MySqlConnection conn = new MySqlConnection(connection))
{
conn.Open();
foreach (DataRow importRow in imported_data.Rows)
{
string query3 = #"INSERT IGNORE INTO try1.modules (NAME, ID_PROJECT) SELECT #NAME, projekty.ID
FROM try1.projects WHERE projects.PROJECT_NAME = #PROJECT_NAME;";
MySqlCommand cmd = new MySqlCommand(query3, conn);
cmd.Parameters.AddWithValue("#NAME", importRow["NAME"]);
cmd.Parameters.AddWithValue("#PROJECT_NAME", importRow["PROJECT_NAME"]);
cmd.ExecuteNonQuery();
}
conn.Close();
}
MessageBox.Show("Imported to database");
}
And event when clicks to btn_import_projects.
private void btn_import_projects_Click(object sender, EventArgs e)
{
DataTable imported_data = ImportFile();
save_modules(imported_data);
frm2.loaddataalldatagridview();
}
when I compiled connected from 3 codes lines to 1 code i had an exception error:
System.ArgumentException: „Column NAME does not belong to table .”
And shows at the line of code:
cmd.Parameters.AddWithValue("#NAME", importRow["NAME"]);
I have a question how to fix this error? Should i change the code lines form cmd.Parameters.AddWithValue to cmd.Parameters.Add? Any ideas? Thx in advance.
UPDATE
for the case for only 1 column the code:
private void save_projects(DataTable imported_data)
{
string connection = "datasource=localhost;port=3306;username=root;password=";
using (MySqlConnection conn = new MySqlConnection(connection))
{
conn.Open();
foreach (DataRow importRow in imported_data.Rows)
{
string query2 = "INSERT IGNORE INTO try1.projects(PROJECT_NAME) VALUES (#PROJECT_NAME);";
MySqlCommand cmd = new MySqlCommand(query2, conn);
cmd.Parameters.AddWithValue("#PROJECT_NAME", importRow["PROJECT_NAME"]);
cmd.ExecuteNonQuery();
}
conn.Close();
}
MessageBox.Show("Imported to database");
}
It works without any small error.
There 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.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Data.OleDb;
using System.IO;
using System.Configuration;
using MySql.Data.MySqlClient;
namespace ControlDataBase
{
public partial class Import_data_mysql : Form
{
public Import_data_mysql()
{
InitializeComponent();
}
New_Tables frm2 = (New_Tables)Application.OpenForms["New_Tables"];
private DataTable ImportFile()
{
DataTable imported_data = new DataTable();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open csv file";
ofd.DefaultExt = "*.csv";
ofd.Filter = "Documents (*.csv)|*.csv";
ofd.ShowDialog();
FileInfo fi = new FileInfo(ofd.FileName);
string FileName1 = ofd.FileName;
string excel = fi.FullName;
using(StreamReader sr = new StreamReader(excel))
{
string header = sr.ReadLine();
if (string.IsNullOrEmpty(header))
{
MessageBox.Show("Not found or loaded not correct file.");
return null;
}
string[] header_columns = header.Split(',');
foreach(string header_column in header_columns)
{
imported_data.Columns.Add(header_column);
}
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (string.IsNullOrEmpty(line)) continue;
string[] fields = line.Split(',');
DataRow imported_row = imported_data.NewRow();
for (int i = 0; i < fields.Count(); i++)
{
imported_row[i] = fields[i];
}
imported_data.Rows.Add(imported_row);
}
}
return imported_data;
}
private void save_modules(DataTable imported_data)
{
string connection = "datasource=localhost;port=3306;username=root;password=";
using (MySqlConnection conn = new MySqlConnection(connection))
{
conn.Open();
foreach (DataRow importRow in imported_data.Rows)
{
string query3 = #"INSERT IGNORE INTO try1.modules (NAME, ID_PROJECT) SELECT #NAME, projekty.ID
FROM try1.projects WHERE projects.PROJECT_NAME = #PROJECT_NAME;";
MySqlCommand cmd = new MySqlCommand(query3, conn);
cmd.Parameters.AddWithValue("#NAME", importRow["NAME"]);
cmd.Parameters.AddWithValue("#PROJECT_NAME", importRow["PROJECT_NAME"]);
cmd.ExecuteNonQuery();
}
conn.Close();
}
MessageBox.Show("Imported to database");
}
private void btn_import_projects_Click(object sender, EventArgs e)
{
try
{
DataTable imported_data = ImportFile();
save_modules(imported_data);
frm2.loaddataalldatagridview();
}
catch
{
MessageBox.Show("Select invalid file to import data.");
}
}
}
}
Ok. Responding to #soohoonigan advice I had to change only two lines of code:
string[] header_columns = header.Split(',');
string[] fields = line.Split(',');
After finding out that in .csb file is seperated with these ";" signs so i've changed these lines to this:
string[] header_columns = header.Split(';');
string[] fields = line.Split(';');
And works correctly. Thanks a alot mates. :)

OLEDB reading Excel File Not Working on IIS asp.net C#

I am trying to Browse the file then Saving that file into one folder and trying to read that file using OLEDB, Everything works file on local as well as working on IIS locally. Same thing when I am released on server it is not working, getting exception as "Access to the path 'C:\inetpub\wwwroot\exceptApp\Files\TemplateFile.xlsx' is denied.", IIS_USERS user has full permission on folder. Below is my code
protected void BtnSubmit_Click(object sender, EventArgs e)
{
try
{
grdResult.DataSource = null;
grdResult.DataBind();
BtnExport.Visible = false;
if (fuFile.HasFile)
{
string readConnString = "";
var fileExtn = Path.GetExtension(fuFile.FileName).ToLower();
var dir = Server.MapPath("~\\Files");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var fileName = Path.GetFileName(fuFile.FileName.Trim());
var fileNameWithPath = Path.Combine(dir, fileName);
if (File.Exists(fileNameWithPath))
{
File.Delete(fileNameWithPath);
}
fuFile.PostedFile.SaveAs(fileNameWithPath);
fuFile.FileContent.Dispose();
//Connection String to Excel Workbook
if (fileExtn.Trim() == ".xls")
{
readConnString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", fileNameWithPath);
}
else if (fileExtn.Trim() == ".xlsx")
{
readConnString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";", fileNameWithPath);
}
using (var dbConn = new OleDbConnection(readConnString))
{
dbConn.Open();
var dt = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
using (var cmd = new OleDbCommand(#"SELECT * FROM [" + dt.Rows[0]["TABLE_NAME"].ToString() + "]", dbConn))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
var resultDt = ds.Tables[0];
dbConn.Close();
if (resultDt.Rows.Count > 0)
{
BtnExport.Visible = true;
grdResult.DataSource = resultDt;
grdResult.DataBind();
}
}
}
Thread.Sleep(1000);
if (File.Exists(fileNameWithPath))
{
File.Delete(fileNameWithPath);
}
}
}
catch (Exception ex)
{
exlog.Log("BtnSubmit_Click", ex.Message);
}
}
You must give access to inetpub folder to IIS_IUSRS on your server.

How to browse Excel file and import using a button

I have two buttons(LoadFile and ImportFile). I want to click load file and browser for Excel file from the directy and then click Import button so that it will load the data into the table in the database. Excel Sheet is called "BankStatement" with more than 1000 rows. I haven't done it before, I am doing this using Linq to SQL .
This is my coding but am not sure how to proceed or get the a way. Can someone please help me. Thanks
Loading
public void LoadExcel()
{
string _LoadPath = #"C:\NewFNBFile1.xls";
TextBox1.Text = _LoadPath.ToString();
var _File = new ExcelQueryFactory(_LoadPath);
_File.AddMapping("Number", "Number");
_File.AddMapping("DateReceived", "DateReceived");
_File.AddMapping("Description1", "Description1"
_File.AddMapping("Description2", "Description2");
_File.AddMapping("Description3", "Description3");
_File.AddMapping("Amount", "Amount");
_File.AddMapping("Balance", "Balance");
_File.AddMapping("AccruedCharges", "AccruedCharges");
}
protected void btnBroswer_Click(object sender, EventArgs e)
{
LoadExcel();
}
Import
protected void btnImport_Click(object sender, EventArgs e)
{
var _list = new ExcelQueryFactory(#"C:\NewFNBFile1.xls");
var _Show = from x in _dc.TESTING_NewBankFile1_s
where x ["Description3"] == "A19C28425645285"
select new
{
Number = x["Number"],
DateReceived = x["DateReceived"],
Description1 = x["Description1"],
Description2 = x["Description2"],
Description3 = x["Description3"],
Amount = x["Amount"],
Balance = x["Balance"],
AccruedCharges = x["AccruedCharges"],
};
}
please refer the below c# code
public System.Data.DataTable GetTable(string filename, string SheetName, string outTableName)
{
OleDbConnection oleConn = null;
OleDbDataAdapter oleAdapter = null;
try
{
string Con = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=" + filename + ";" +
#"Extended Properties=" + Convert.ToChar(34).ToString() +
#"Excel 12.0;" + "Imex=1;" + "HDR=Yes;" + Convert.ToChar(34).ToString() ;
oleConn = new OleDbConnection(Con);
oleConn.Open();
OleDbCommand oleCmdSelect = new OleDbCommand();
oleCmdSelect = new OleDbCommand(
#"SELECT * FROM ["
+ SheetName
+ "$" + "]", oleConn);
oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = oleCmdSelect;
System.Data.DataTable dt = new System.Data.DataTable(outTableName);
oleAdapter.FillSchema(dt, SchemaType.Source);
oleAdapter.Fill(dt);
oleCmdSelect.Dispose();
oleCmdSelect = null;
oleAdapter.Dispose();
oleAdapter = null;
oleConn.Dispose();
oleConn = null;
return dt;
}
}

Getting error after updating image in Sql server 2008 database

I am developing a winform application in VS 2010 C#.
I have developed a form to insert and update the user details in this.
My Update user form is as below image
![Update User Screen][1]
http://i.stack.imgur.com/iZaAJ.png
And coding to update is
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.SqlClient;
using Microsoft.VisualBasic;
using System.Drawing.Imaging;
using System.IO;
namespace SampleApplication
{
public partial class UserUpdate : Form
{
public UserUpdate()
{
InitializeComponent();
}
SqlDataAdapter da;
SqlConnection con = new SqlConnection("user id=sa; password=123;initial catalog=Inventory;data source=Aniket-PC");
SqlCommand cmd;
MemoryStream ms;
byte[] photo_array;
DataSet ds;
int rno = 0;
string str;
private void nameTxt_Validating(object sender, CancelEventArgs e)
{
if (nameTxt.Text.Trim().Length == 0)
{
namewarning.Visible = true;
}
else
{
namewarning.Visible = false;
}
}
private void Update_Load(object sender, EventArgs e)
{
contTxt.MaxLength = 10;
retriveData();
retriveImg();
}
void retriveImg()
{
con.Open();
cmd = new SqlCommand("Select Logo from Register where UserName='" + uNameTxt.Text + "'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet("MyImage");
da.Fill(ds, "MyImage");
DataRow myRow;
myRow = ds.Tables["MyImage"].Rows[0];
photo_array = (byte[])myRow["Logo"];
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
con.Close();
}
void retriveData()
{
con.Open();
cmd = new SqlCommand("Select * from Register where UserName='"+uNameTxt.Text+"'",con);
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
nameTxt.Text = (read["Name"].ToString());
passTxt.Text = (read["Password"].ToString());
conPassTxt.Text = (read["Password"].ToString());
emailTxt.Text = (read["EmailId"].ToString());
addTxt.Text = (read["Address"].ToString());
contTxt.Text = (read["ContactNo"].ToString());
DORTxt.Text = (read["DOR"].ToString());
validity.Text = "Account Valid till "+(read["Validity"].ToString());
}
read.Close();
con.Close();
}
private void AttachBtn_Click(object sender, EventArgs e)
{
// Open image by OpenFiledialog and show it in PicturBox.
try
{
//filter only image format files.
openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
DialogResult res = openFileDialog1.ShowDialog();
if (res == DialogResult.OK)
{
Image img = new Bitmap(openFileDialog1.FileName);
//inserting image in PicturBox
profPic.Image = img.GetThumbnailImage(127, 128, null, new IntPtr());
openFileDialog1.RestoreDirectory = true;
}
}
catch
{
MessageBox.Show("Cannot upload image");
}
}
private void UpdateBtn_Click_1(object sender, EventArgs e)
{
string DOM = dateTimePicker1.Value.ToShortDateString();
if (namewarning.Visible == true || picError.Visible == true || PassError.Visible == true || emailwarningImg.Visible == true)
{
MessageBox.Show("Please correct the marked fields");
}
else
{
//cmd = new SqlCommand("update Register set (Name,Password,EmailId,Address,ContactNo,Logo,DOM) values('" + nameTxt.Text.Trim() + "','" + passTxt.Text.Trim() + "','" + emailTxt.Text.Trim() + "','" + addTxt.Text.Trim() + "','" + contTxt.Text.Trim() + "',#Logo,'" + DOM+ "')", con);
str = string.Format("update Register set Name='{0}', Password='{1}',EmailID='{2}',Address='{3}',ContactNo='{4}',Logo='{5}',DOU='{6}' where UserName='{7}'", nameTxt.Text.Trim(), passTxt.Text.Trim(), emailTxt.Text.Trim(),addTxt.Text.Trim(), contTxt.Text.Trim(), #"Logo" ,DOM,uNameTxt.Text);
con_photo();
//con.Open();
cmd = new SqlCommand(str, con);
int count= cmd.ExecuteNonQuery();
if (count > 0)
MessageBox.Show("Sucsess");
else
MessageBox.Show("need to work");
}
}
void con_photo()
{
if (profPic.Image != null)
{
ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_array = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_array, 0, photo_array.Length);
cmd.Parameters.AddWithValue("#Logo", photo_array);
}
}
when i run the application it executes very well and shows me success message but when i again try to view the update user form it shows below screenshot error
http://i.stack.imgur.com/7z1Rx.png
at retriveImg ()
Please help me with resolution for this..
You're not passing the image bytes to the UPDATE command, but a string containing the word Logo.
Also: PLEASE avoid creating SQL commands using string concatenation or String.Format. Use parameterized queries instead!
Also: Do not use an NVARCHAR field to store the image bytes (unless you create a BASE64 string from them first), but use a VARBINARY or IMAGE column instead.
The problem is in the following line:
str = string.Format("update Register set ... ,Logo='{5}' ...", ..., #"Logo", ...);
As you can see, you're formatting a string, but you don't insert the bytes from the image, but the word "Logo".
Assuming the column Logo was of type IMAGE or VARBINARY, I would write something like this:
byte[] photo_array = null;
if (profPic.Image != null)
{
MemoryStream ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
photo_array = ms.GetBuffer();
}
if (photo_array != null)
{
SqlCommand cmd = new SqlCommand("UPDATE Register SET Logo=#logo", connection);
cmd.Parameters.AddWithValue("#logo", imageBytes);
cmd.ExecuteNonQuery();
}
Maybe I'm wrong but I'll try to do this
photo_array = (byte[])myRow["Logo"];
if photo_array.length.trim()>0
{
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
}
con.Close();
This error may come when the lenght of the string is 0
Another thing is that you're not saving the image in the database
//C# Code
SqlCommand cmdSelect = new SqlCommand("select ImageValue from table where ID=1", ObjCon);
ObjCon.Open();
byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
ObjCon.Close();
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream("C:\\Temp\\1.txt", FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
// 1.txt file will be created in c:\temp folder

Uploading an Excel sheet and importing the data into SQL Server database

I am developing this simple application to upload an Excel file (.xlsx) and import the data present in that Excel worksheet into a SQL Server Express database in .NET
I'm using the following code on click of the import button after browsing and selecting the file to do it.
protected void Button1_Click(object sender, EventArgs e)
{
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";
//file upload path
string path = FileUpload1.PostedFile.FileName;
//string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
But the code doesn't run when I use
string path = FileUpload1.PostedFile.FileName;`
and even
string path="C:\ Users\ Hemant\Documents\example.xlsx";`
The dReader is unable to take the path in this format.
It is only able to take path in the following format
string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
i.e. with the the \\ in the path.For which I have to hard code the path but we have to browse the file.
So,can any one please suggest a solution to use the path taken by the FileUpload1 to import the data?
You are dealing with a HttpPostedFile; this is the file that is "uploaded" to the web server. You really need to save that file somewhere and then use it, because...
...in your instance, it just so happens to be that you are hosting your website on the same machine the file resides, so the path is accessible. As soon as you deploy your site to a different machine, your code isn't going to work.
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!
Not sure why the file path is not working, I have some similar code that works fine.
But if with two "\" it works, you can always do path = path.Replace(#"\", #"\\");
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)
Example:
private static void DataReaderBulkCopySample()
{
using (var reader = new ExcelDataReader(#"test.xlsx"))
{
var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);
using (var bulkCopy = new SqlBulkCopy(ConnectionString))
{
// MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess,
// optimizing memory usage by using the IDataReader streaming capabilities
bulkCopy.EnableStreaming = true;
bulkCopy.DestinationTableName = TableName;
foreach (var col in cols)
bulkCopy.ColumnMappings.Add(col, col);
bulkCopy.WriteToServer(reader);
}
}
}
Try Using
string filename = Path.GetFileName(FileUploadControl.FileName);
Then Save the file at specified location using:
FileUploadControl.PostedFile.SaveAs(strpath + filename);
public async Task<HttpResponseMessage> PostFormDataAsync() //async is used for defining an asynchronous method
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var fileLocation = "";
string root = HttpContext.Current.Server.MapPath("~/App_Data");
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root); //Helps in HTML file uploads to write data to File Stream
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
fileLocation = file.LocalFileName + filePath; //Complete file location
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public void ReadFromExcel()
{
try
{
DataTable sheet1 = new DataTable();
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = fileLocation;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
string selectSql = #"SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
connection.Open();
adapter.Fill(sheet1);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
A proposed solution will be:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
CreateXMLFile();
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand("bulk_in", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#account_det", sw_XmlString.ToString ());
int i= cmd.ExecuteNonQuery();
if(i>0)
{
Label1.Text = "File Upload successfully";
}
else
{
Label1.Text = "File Upload unsuccessfully";
return;
}
con.Close();
}
catch(SqlException ex)
{
Label1.Text = ex.Message.ToString();
}
}
public void CreateXMLFile()
{
try
{
M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
fileExtn = Path.GetExtension(M_Filepath);
strGuid = System.Guid.NewGuid().ToString();
fNameArray = M_Filepath.Split('.');
fName = fNameArray[0];
xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-');
fileName = xlRptName.Trim() + fileExtn.Trim() ;
FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName);
strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ;
if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX"))
{
Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX";
}
FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName);
lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName;
if (strFileName == "DEMO.XLS")
{
strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
}
if (strFileName == "DEMO.XLSX")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'";
}
strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]";
OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn);
mydata.TableMappings.Add("Table", "arul");
mydata.Fill(dsExcl);
dsExcl.DataSetName = "DocumentElement";
intRowCnt = dsExcl.Tables[0].Rows.Count;
intColCnt = dsExcl.Tables[0].Rows.Count;
if(intRowCnt <1)
{
Label1.Text = "No records in Excel File";
return;
}
if (dsExcl==null)
{
}
else
if(dsExcl.Tables[0].Rows.Count >= 1000 )
{
Label1.Text = "Excel data must be in less than 1000 ";
}
for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++)
{
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString();
}
if (strValid == "")
{
Label1.Text = "Name should not be empty";
return;
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString();
}
if (strValid == "")
{
Label1.Text = "Mobile_num should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString();
}
if (strValid == "")
{
Label1.Text = "Account_number should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString();
}
if (strValid == "")
{
Label1.Text = "Amount should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString();
}
if (strValid == "")
{
Label1.Text = "date_a2 should not be empty";
}
else
{
strValid = "";
}
}
}
catch
{
}
try
{
if(dsExcl.Tables[0].Rows.Count >0)
{
dr = dsExcl.Tables[0].Rows[0];
}
dsExcl.Tables[0].TableName = "arul";
dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema);
}
catch
{
}
}`enter code here`
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
protected void btnUpload_Click(object sender, EventArgs e)
{
divStatusMsg.Style.Add("display", "none");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "";
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
{
GetExcelSheetForEmployeeCode(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";
}
}
}
}
private void GetExcelSheetForEmployeeCode(string filename)
{
int count = 0;
int selectedcheckbox = 0;
string empcodeexcel = "";
string empcodegrid = "";
string excelFile = "Employee/DateExcel" + filename;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet ds = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
// Create connection.
objConn = new OleDbConnection(connString);
// Opens connection with the database.
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
// Get the data table containing the schema guid, and also sheet names.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
if (ds.Tables[0].ToString() != null)
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
for (int k = 0; k < GrdEmplist.Rows.Count; k++)
{
empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
date.Value = ds.Tables[0].Rows[j][1].ToString();
Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
empcodegrid = lbl_Code.Text;
CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");
if ((empcodegrid == empcodeexcel) && (date.Value != ""))
{
chk.Checked = true;
txt_Sal.Text = date.Value;
selectedcheckbox = selectedcheckbox + 1;
lblSelectedRecord.InnerText = selectedcheckbox.ToString();
count++;
}
if (chk.Checked == true)
{
}
}
}
}
}
i++;
}
}
catch (Exception ex)
{
ShowMessage(ex.Message.ToString(), 0);
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "EmpExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdByExcel.DataSource = dss.Tables[0].DefaultView;
grdByExcel.DataBind();
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdByExcel.DataSource = null;
grdByExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}

Categories