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();
}
}
}
}
Related
I need upload Excel File and then read and import its data into DataTable using C# in ASP.Net Web Application.
The imported Excel File data is then displayed in ASP.Net GridView control.
I'm using the code below but I have problem with column "AV" on the Excel File
The column "AV" contains these values
But in gridview output I have
In gridview output I don't have the numbers of Excel file source, but only "-" values
Any suggestion?
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
Master.PleaseWait();
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string FilePath = Server.MapPath(FolderPath + FileName);
FileUpload1.SaveAs(FilePath);
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
}
}
private void Import_To_Grid(string FilePath, string Extension, string isHDR)
{
string conStr = "";
switch (Extension)
{
case ".xls":
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
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;
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
connExcel.Open();
cmdExcel.CommandText = "SELECT * From[" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
I made a program to open Excel file.
There are exist data page and blank page.
Can I add only the pages where the data exists in the combo box?
Can I use ButtonEvent to view only pages that contain data?
string filePath = openFileDialog1.FileName;//파일 경로 가져오기
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
//string connectionString = string.Empty;
string sheetName = string.Empty;
using (OleDbConnection con = new OleDbConnection(ConnectStr()))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
public string ConnectStr()
{
string filePath = openFileDialog1.FileName;
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
string connectionString = string.Empty;
string sheetName = string.Empty;
switch (fileExtension)
{
case ".xls": //Excel 97-03버전
connectionString = string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07이상 버전
connectionString = string.Format(Excel16ConString, filePath);
break;
}
return connectionString;
}
I don't really get what is this. But I beg you need to show only specific sheet from spreadsheet correct me if i'm wrong.
There is a SQL commend that we can query from the specific sheet.
try
{
this.txtImportFilePath.Text = opd.FileName;
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + this.txtImportFilePath.Text + ";Extended Properties=Excel 8.0;");
StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("Select * From [Sheet1$]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
DataView dvEmp = new DataView(dsXLS.Tables[0]);
trnxlistDataview.DataSource = dvEmp;
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
I have this piece of code, and I am trying to import data from an Excel File to SQL server using ASP.net but it is throwing an error and I cant Figure Out Why?
when compiled it says The Connection String property has not been initialized. any help is appreciated thanks ?
protected void LoadFile(object sender, EventArgs e)
{
{
//Upload and save the file
string excelPath = Path.GetFileName(FileUpload1.PostedFile.FileName);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
break;
case ".xlsx": //Excel 07 or higher
conString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
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]["toll"].ToString();
DataTable dtExcelData = new DataTable();
dtExcelData.Columns.AddRange(new DataColumn[4] {
new DataColumn("Tag", typeof(string)),
new DataColumn("Exit",typeof(string)),
new DataColumn("Location",typeof(string)),
new DataColumn("Amount",typeof(decimal)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
using (SqlConnection con = new SqlConnection(ConString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "MY Table";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Amount", "Amount");
sqlBulkCopy.ColumnMappings.Add("Tag", "Tag");
sqlBulkCopy.ColumnMappings.Add("Exit", "Exit");
sqlBulkCopy.ColumnMappings.Add("Exit", "Exit");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
I have few columns in my excel sheet -> Job, Hours, Notes
There is a table in my database 'Tasks', where I have columns -> Task, Hours, Comment.
I have to read data from Excel file through ASP.Net page and import all data to SQL server database.
I have added FileUpload for excel file browsing and a button event to read the data.
I have seen this code:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string FilePath = Server.MapPath(FolderPath + FileName);
FileUpload1.SaveAs(FilePath);
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
}
}
private void Import_To_Grid(string FilePath, string Extension, string isHDR)
{
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();
}
But this binds with the GridView and I want to update my database. Any recommendations how that can be achieved?
Not clear. but if it is what I think it is then :
Before
//Bind Data to GridView
GridView1.Caption = Path.GetFileName(FilePath);
GridView1.DataSource = dt;
GridView1.DataBind();
You can have an update function called which will update the database. There is not update or interaction with database here.
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");
}