Excel contents into SQL Server table using Visual Studio 2008 - c#

I'm creating an application where the user clicks on a button, browses for an Excel file, and the data is copied into the data table created in the database.
I am using VS2008 and SQL Server 2005.
I wrote code for opening the file of course, and created a dataTable and its dataColumns in the .cs file. What else should I do?
Thank you.

You could do as Krishna advises... but that code will only work if the columns in the excel file and Database columns are the same in number and order. For ease of maintainability and mapping down the line I highly recommend you use a combination of Linq to Excel and Linq to SQL as in this article:
http://solidcoding.blogspot.com/2008/01/linq-to-excel-sql-import.html

You can write like the code below to dump the data into the SQL Server table
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("ImportFile.xls") + ";Extended Properties=""Excel 8.0;HDR=Yes;""";
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [NameOfTheDataSheet$]", connection);
connection.Open();
using (DbDataReader dataReader = command.ExecuteReader())
{
string sqlConnectionString = "SQL Connection String";
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelDataTable";
bulkCopy.WriteToServer(dataReader);
}
}
}
Let me know if you have different requirements.

Related

How to import bulk data to sql server from excel/csv

My requirement is that i have 2l data in excel/CSV file which has email id in each row, I have to import those data at one shot, i.e bulk copy to SQL server by verifying one data(email) at a time.
You could also use Microsoft Visual Studio's Business Intelligence tools. By creating a SSIS (SQL Server Integration Services) project you can use various drag and drop tools to create "packages" (or jobs if you wish) which you can execute to perform jobs like these.
You can import data from a wide variety of data sources including Excel, CSV, MySQL, SQL Server and Hadoop to name a few.
You can also write that data from those sources to not only SQL Server but a wide variety of other data destinations as well.
I am using Visual Studio 2015 with the Business Intelligence packages installed.
What I would recommend is:
Start Visual Studio and open a new SSIS (SQL Server Integration Services) project.
Under the control flow tab. Add a new Data Flow task to the control flow area.
Double click on the control flow item or navigate to the Data Flow tab.
Make sure you data flow item is selected. (Should be if you double clicked it.)
From there you can use the Source and Destination Assistants to transport your data.
Once done setting up you source, destination, data transformations and checks. You can hit Start and it will execute the package.
P.S: You can also use the script component in the data flow tab to write custom C# script if you want to.
If we had an example of the Schema (Table structure) you were transporting from and to it would have helped with providing an example.
Best of luck
I have specified the connection strings for the Excel files of both 2003 and 2007 or higher formats in the Web.Config file.
<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 will need to import the following namespaces.
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
Add the following code :
//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[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Salary",typeof(decimal)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.tblPersons";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Id", "PersonId");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Salary", "Salary");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}

alternate for Oleb DB importing excel file

Maybe someone can help me with the following problem:
I want to import a excel file and read the columns in to the database. I used OleDB provider so far:
string constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
using (OleDbConnection conn = new OleDbConnection(constr))
{
conn.Open();
OleDbCommand command = new OleDbCommand("Select * from [Sheet1$]", conn);
OleDbDataReader reader = command.ExecuteReader();
is there an alternate for doing this without OleDB? im getting the following errormessage:The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. and i dont have the option to install ole DB on the environment where the application is running.
thanks

Fetch MS Access Data Using C# in Table or Formatted Form

I am bit new on c# Window application Development, i have developed lots of working applications in c#, and now i am working on Database using MS Access ODBC. I get success in data insertion into Database but now i am fetching the data, and facing issue of not getting data into the form.
So please can anybody let me know the best way to fetch Data from MS Access Database using c# in an proper table form.
string connectionString = #"Provider=Microsoft Office 12.0 Access Database Engine OLE DB Provider;" + #"Data source= C:\Users\user\Documents\Visual Studio 2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\bin\debug\Database21.accdb";
string queryString = "SELECT * FROM newdb2";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
while (reader.Read())
{
reddd.Text = reader.GetString(0).ToString();
reddf.Text = reader.GetString(1).ToString();
// Insert code to process data.
}
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Source);
}

How to create a graph in C# using SQL Server database?

I'm using a SQL Server database and C# form, I want to create a graph in C# form with database data.
I use msdn sample codes but it didn't work; no error and no response!
Thank you for helping me ;)
// The Access database
string fileNameString = "data\\chartdata.mdb";
// Initialize a connection string
string myConnectionString = "Data Source=" + fileNameString;
// Define the database query
string mySelectQuery="SELECT Name, Sales FROM REPS ;";
// Create a database connection object using the connection string
SqlConnection myConnection = new SqlConnection(myConnectionString);
// Create a database command on the connection using query
SqlCommand myCommand = new sqlCommand(mySelectQuery, myConnection);
// Open the connection
myCommand.Connection.Open();
// Create a database reader
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
chart1.Series["Default"].Points.DataBindXY(myReader, "Name", myReader, "Sales");
// Close the reader and the connection
myReader.Close();
myConnection.Close();
you can install and Use reporting services to create graph report and dashboard.
MSDN link for SSRS

Getting different errors while importing Excel file through SqlBulkCopy

I am importing an Excel file into SQL Server using SqlBulkCopy
But every time I get differant errors like
Cannot update. Database or object is read-only.
or
Could not find installable ISAM.
or
The Microsoft Jet database engine could not find the object. Make sure the object exists and that you spell its name and the path name correctly.
Check my code below...
String strConnection = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filepath+";Extended Properties=Excel 8.0;HDR=YES;";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select * from [Sheet1$]",
excelConnection);
MessageBox.Show("ss");
excelConnection.Open();
MessageBox.Show("ss2");
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
MessageBox.Show("ss1");
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "RecExcelTable";
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
Also I need to compitable this code for any version of Excel.
How can I do that and solve my error?
I had similar issue. Check that the file path is correct
do like
C:\\file.xls
as a test.
And also check that the version is correct. 8.0 is pretty old I think thats like office 2000, no ?

Categories

Resources