Inserting Excel sheet into SQL Server database - c#

I am trying to insert an Excel sheet into a SQL Server database from datagridview using OleDb.
The code that I use :
namespace importfromexcel
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True");
// SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
private void button2_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;data source=" + ofd.FileName + #";Extended Properties=Excel 8.0;";
// Create Connection to Excel Workbook
//We can Import excel to sql server like this
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select fname,lname FROM [sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True";
// SqlCommand cmd;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "test";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
}
My database name is : mohammed and the table name is test with two columns firstname and lastname and the Excel sheet columns is fname and lname ..
The problem is that when I execute the code and after insert the Excel sheet from button2
when I click button1 and I got an window error
vshot32-clr2.exe has stopped working
Any help please ??

I don't know if it's the root cause, but you're referencing ofd.FileName in your Click event when there's no guarantee that the dialog has a valid file selected. Since you're storing that value in a text box I would change it to:
string excelConnectionString =
#"Provider=Microsoft.Jet.OLEDB.4.0;data source="
+ textBox1.Text
+ #";Extended Properties=Excel 8.0;";
I would also verify that you're able to query the data (e.g. by writing to a text file) as a test before trying to implement bulk copy. Also be aware that the source data must have exactly the same structure (including column order) unless you supply a ColumnMapping.

Sql server has a import tool called Sql Server Data Tools... there you can find a activity to import from a excel file... very "end-user" deal, by that i mean the you can configure everything on drag and drop basis...

In your extended properties for the excel connection string, you may wish to set HDR=YES and IMEX=1. HDR=YES will read the first row in your excel sheet and read the data stored in each cell as a column name. IMEX=1 tells JET to insert the data regardless of datatype from each cell.
Have a look at this code I have written myself, it may help you.
//ExcelDA Class
public ExcelDA()
{
connString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + ofd.FileName + "; Extended Properties=" + '"' + "Excel 8.0; HDR=Yes; IMEX=1" + '"';
}
/// <summary>
/// Method used to retrieve a datatable from excel sheet
/// </summary>
public DataTable GetProductsExcel()
{
StringBuilder excBuilder = new StringBuilder();
excBuilder.Append("SELECT * FROM [Sheet1$];");
//
try
{
return ExecuteSqlStatement(excBuilder.ToString());
}
catch (Exception)
{
MessageBox.Show("Error retreiving data");
return null;
}
}
private DataTable ExecuteSqlStatement(string command)
{
using (OleDbConnection conn = new OleDbConnection(connString))
{
try
{
conn.Open();
using (OleDbDataAdapter adaptor = new OleDbDataAdapter(command, conn))
{
DataTable table = new DataTable();
adaptor.Fill(table);
return table;
}
}
catch (SqlException e)
{
throw e;
}
}
}
//SqlDA class
public void ExecuteSQLCommand(string comm)
{
try
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(comm, conn))
{
command.ExecuteNonQuery();
}
}
}
catch (ArgumentOutOfRangeException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
catch (SqlException ex) { throw ex; }
}
public void AddNames(string fName, string sName)
{
StringBuilder sqlQuery = new StringBuilder();
//build sql insert statement here
ExecuteSQLCommand(sqlBuilder.ToString());
}
//Program class
ExcelDA reader = new ExcelDA();
DataTable names = reader.GetSuppliersExcel();
//string array to store excel row data for names
string[] arr2 = new string[2] { "", ""};
//recursive loop to retrieve each row and values from each rows columns
foreach (DataRow row in suppliers.Rows)
{
for (int i = 0; i < names.Columns.Count; i++)
{
if (i == (names.Columns.Count - 1))
{
arr2[i] = (row[i].ToString());
}
else
{
arr2[i] = (row[i].ToString());
}
}
}
try
{
sql.AddNames(arr2[0], arr2[1]);
Console.WriteLine("Added Data to SQL");
}
catch (Exception) { }

Related

c# Excel, the provider 'microsoft.ace.oledb.12.0' is not registered

I am working on a c# project where I need the user to open an Excel file and insert the data in an SQL server database. The problem is that using this connection string
("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;")
during the opening of the connection I get
the provider 'microsoft.ace.oledb.12.0' is not registered
exception, which is odd because I worked with an Access Database and used the same connection string. The Access Database Engine is installed on my PC and I even compiled at x86, am I missing something?
The reasons are as follows:
When accessing the .xlsx file with SQL SERVER, you must use
provider 'Microsoft.ACE.OLEDB.12.0' to implement.
First install AccessDatabaseEngine.exe.
Download path: http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
This provider can be seen in the database on 32-bit systems.
It cannot be seen in a 64-bit system, so you need to call
C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\DTExec.exe
to execute the package.
solution:
Open IIS Manager.
Right-click the connection pool where the application is located.
Modify "Enable 32 as application" to true.
The code shown below may help you.
Sqlconn sqlcon = new Sqlconn();
public Form1()
{
InitializeComponent();
}
string str_Excel_Path;
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Only one file can be opened------------------------------------------
openFileDialog1.Filter = "Excel file|*.xlsx";//Set the open file filter
openFileDialog1.Title = "Open Excel file";//Set the title of the open file
openFileDialog1.Multiselect = true;//Allow multiple files to be selected
if (openFileDialog1.ShowDialog() == DialogResult.OK)//Determine whether a file is selected
{
str_Excel_Path = openFileDialog1.FileName.ToString();//Get the selected file address
textBox1.Text = str_Excel_Path;//Display the selected file address in textBox1
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string[] P_str_Names = textBox1.Text.Split(',');//Store all selected Excel file names
string P_str_Name = "";//Store the traversed Excel file name
List<string> P_list_SheetNames = new List<string>();//Create a generic collection object to store sheet names
for (int i = 0; i < P_str_Names.Length; i++)//Iterate over all selected Excel file names
{
P_str_Name = P_str_Names[i];//The Excel file name traversed by the record
P_list_SheetNames = GetSheetName(P_str_Name);//Get all sheet names in the Excel file
for (int j = 0; j < P_list_SheetNames.Count; j++)//traverse all worksheets
{
/* if (ckbox_Windows.Checked)//Log in to SQL Server with Windows authentication
//Export worksheet contents to SQL Server
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "';Initial Catalog='" + cbox_Server.Text + "';Integrated Security=True;");
}
else if (ckbox_SQL.Checked)//Log in to SQL Server with SQL Server authentication
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "'Database='" + cbox_Server.Text + "';Uid='" + txt_Name.Text + "';Pwd='" + txt_Pwd.Text + "';");
}*/
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456");
}
}
MessageBox.Show("All selected Excel sheets have been imported into SQL Server database!", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Please select the file to be imported into the database!");
}
}
//Get all worksheet names in the Excel file
private List<string> GetSheetName(string P_str_Name)
{
List<string> P_list_SheetName = new List<string>();//Create a generic collection object
//Connect to the Excel database
//OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Name + ";Extended Properties=Excel 8.0;");
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Name + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"");
olecon.Open();//Open database connection
System.Data.DataTable DTable = olecon.GetSchema("Tables");//Create a table object
DataTableReader DTReader = new DataTableReader(DTable);//Create table read object
while (DTReader.Read())
{
string p_str_sName = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim();//Record the worksheet name
if (!P_list_SheetName.Contains(p_str_sName))//Determine whether the sheet name already exists in the generic collection
P_list_SheetName.Add(p_str_sName);//Add the worksheet to the pan-collection
}
DTable = null;//Clear the table object
DTReader = null;//Clear the table read object
olecon.Close();//Close the database connection
return P_list_Sheet
}
/* Import the content of the specified worksheet in Excel into the SQL Server database */
public void ImportDataToSql(string p_str_Excel, string p_str_SheetName, string p_str_SqlCon)
{
DataSet myds = new DataSet();//Create a dataset object
try
{
// get all data
//string P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + p_str_Excel + ";Extended Properties=Excel 8.0;";
string P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + p_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"";
OleDbConnection oledbcon = new OleDbConnection(P_str_OledbCon);//Create an Oledb database connection object
string p_str_ExcelSql = "";//Record the Excel query statement to be executed
OleDbDataAdapter oledbda = null;//Create an Oledb data bridge object
p_str_ExcelSql = string.Format("select * from [{0}$]", p_str_SheetName);//Record the Excel query statement to be executed
oledbda = new OleDbDataAdapter(p_str_ExcelSql, P_str_OledbCon);//Execute Excel query using data bridge
oledbda.Fill(myds, p_str_SheetName);//Fill data
//Define variables to record the SQL statement that creates the table
string P_str_CreateSql = string.Format("create table {0}(", p_str_SheetName);
foreach (DataColumn c in myds.Tables[0].Columns)//traverse all rows in the dataset
{
P_str_CreateSql += string.Format("[{0}]text,", c.ColumnName);//Create a field in the table
}
P_str_CreateSql = P_str_CreateSql + ")";//Improve the SQL statement for creating a table
//Create SQL database connection object
using (SqlConnection sqlcon = new SqlConnection(p_str_SqlCon))
{
sqlcon.Open();//Open database connection
SqlCommand sqlcmd = sqlcon.CreateCommand();//Create an execution command object
sqlcmd.CommandText = P_str_CreateSql;//Specify the SQL data to be executed
sqlcmd.ExecuteNonQuery();//Execute operation
sqlcon.Close();//Close the database connection
}
using (SqlBulkCopy bcp = new SqlBulkCopy(p_str_SqlCon))//Import data with bcp
{
bcp.BatchSize = 100;//Number of rows per transfer
bcp.DestinationTableName = p_str_SheetName;//Define the destination table
bcp.WriteToServer(myds.Tables[0]);//Write data to SQL server data table
}
}
catch
{
MessageBox.Show("SQL Server database already exists" + p_str_SheetName + "Table!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Sqlconn code:
// private static string constr = "server=(local);Initial Catalog=D_total;Integrated Security=True";
private static string constr = "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456";
// private static string constr = "Data Source =192.168.1.201;Initial Catalog=D_total23 ;User Id=sa;Password=123";
public DataTable f1()
{
string A = "select name from master..sysdatabases";//Query this database information
return Only_Table1(A);
}
public DataTable Only_Table1(string exec)
{
System.Data.DataTable dt_jdl = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
if (con.State == ConnectionState.Open || con.State == ConnectionState.Connecting)
{
SqlDataAdapter sda2 = new SqlDataAdapter(exec, con);//All by writing stored procedures
DataSet ds2 = new DataSet();
sda2.Fill(ds2, "cxq");
dt_jdl = ds2.Tables["cxq"];
sda2.Dispose();
ds2.Dispose();
}
con.Close();
}
return dt_jdl;
}
catch (Exception EX)
{
return null;
}
}
}
Run the project:
Click the OK button to select the xml file from the folder. Click the import button to import the file into the database.

How to create a Treeview from CSV after uploading it into a Dataset in C#?

I am new to C#. I decided to try and make a program for my department that users can load a CSV and look up Serial Numbers and Names associated with them. In my program, I am importing a CSV file into a DataViewGrid and displaying it.
Is it possible to then take the information I just loaded,and display it in a TreeView?
The information in the CSV currently contains only 2 headers, but I would like to add more. The first column is a Serial Number, and the second column is a Name.
Thanks in advance for any help.
Below is how I import the CSV.
public DataTable ReadCsv(string fileName)
{
DataTable dt = new DataTable("Data");
using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
Path.GetDirectoryName(fileName) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)';"))
{
using (OleDbCommand cmd = new OleDbCommand(string.Format("select *from [{0}]", new FileInfo(fileName).Name), cn))
{
cn.Open();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
adapter.Fill(dt);
}
}
}
return dt;
}
//Button Open
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
dataGridView1.DataSource = ReadCsv(ofd.FileName);
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); //Autosize columns
label1.Text = ofd.FileName + " Loaded"; //Label update
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Unable To Read CSV", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

How can we import excel file to Sql server table where excel table columns are not in order as Sql table

I have an excel file whose worksheets name same as SQL table name but the column mapping is failing as both have same columns but the order of columns are different , please help me on this.
Edited: Added another example at the end.
One of many ways of implementing what you ask is to import worksheet as a datatable in c# and then Insert the data with SqlBulkCopy (SqlBulkCopy (MSDN)). This method is better for large files because SqlBulkCopy uses bulk insert command.
For the first step (import file as datatable) you have many options such as using OLEDB for xls or xlsx (you can use my example or others such as this link or this), using third-party libraries such as easyxls.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.DataSet DtSet ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
After that for second step you can use SQLBulkCopy with column mapping to map the dataTable columns to your database table columns.
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoDifferentColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Set up the bulk copy object.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connectionString))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoDifferentColumns";
// Set up the column mappings by name.
SqlBulkCopyColumnMapping mapID =
new SqlBulkCopyColumnMapping("ProductID", "ProdID");
bulkCopy.ColumnMappings.Add(mapID);
SqlBulkCopyColumnMapping mapName =
new SqlBulkCopyColumnMapping("Name", "ProdName");
bulkCopy.ColumnMappings.Add(mapName);
SqlBulkCopyColumnMapping mapMumber =
new SqlBulkCopyColumnMapping("ProductNumber", "ProdNum");
bulkCopy.ColumnMappings.Add(mapMumber);
// Write from the source to the destination.
try
{
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
private static string GetConnectionString()
// To avoid storing the sourceConnection string in your code,
// you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
"Initial Catalog=AdventureWorks;";
}
}
another example of SqlBulkCopy usage:
public bool CopyTransactionDataToTable(DataTable Dt, long ProductID)
{
try
{
SqlBulkCopy copy = new SqlBulkCopy(Adapter.GetActiveConnection().ConnectionString);
Collection = mapping.LoadMappedNameEntityByProductID(ProductID);
copy.ColumnMappings.Add("ProductID", "ProductID");
copy.ColumnMappings.Add("ResellerID", "ResellerID");
copy.ColumnMappings.Add("Status", "Status");
copy.ColumnMappings.Add("PK_ID", "TxID");
copy.DestinationTableName = "TBLProdect";
copy.BulkCopyTimeout = ConfigurationSettings.AppSettings.Get(UIConstants.SQLTimeOut).ToInt32();
copy.WriteToServer(Dt);
Adapter.CommandTimeOut = copy.BulkCopyTimeout;
return true;
}
catch (Exception ex)
{
Log.Error(ex);
return false;
}
}
You didn't indicate if you were looking to make this repetitive, or programmatic, etc - but two other options would be to use the SQL Server Data Import/Export Wizard
https://msdn.microsoft.com/en-us/library/ms141209.aspx
Another option would be to use SQL Server Integration Services (SSIS)
http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/

How to fill a combobox from a MS Access text field then insert combobox selection into another table

I am trying to insert an Access table record with information from a combobox. I am using a winform and C#. I have simplified my project to just include the problem area. I am showing three methods with 4 controls (2 buttons and 2 comboboxes. The first method is connecting to an Access database and then showing a list of the tables and views in the first combobox. this method will also call the last method, SelectName() and fill the second combobox with field contents from a predetermined table from the selected database. The second method (buttonInsert_Click()) is where my problem lies. I would like the method to insert into one of the selected tables from combobox1 the selected item from combobox2 when the insert button is clicked. The only content I can get to insert into the selected table is
System.Data.DataRowView
The C# section of my project is below. Any suggestions are appreciated. Thank You.
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 DbApp
{
public partial class Form1 : Form
{
private char ch = '"';
private OleDbConnection dbConn;
private string sql = "";
public Form1()
{
InitializeComponent();
}
private void buttonConnect_Click(object sender, EventArgs e)
{
string connectionString = "";
string stringData = "";
openFileDialog1.Filter = "";
openFileDialog1.ShowDialog();
Text = openFileDialog1.FileName;
stringData = openFileDialog1.FileName;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + Text + ch;
if (dbConn != null)
dbConn.Close();
dbConn = new OleDbConnection(connectionString);
dbConn.Open();
comboBox1.Items.Clear();
DataTable info = dbConn.GetSchema("Tables");
for (int x = 0; x < info.Rows.Count; ++x)
{
if ((info.Rows[x][3].ToString() == "TABLE") || (info.Rows[x][3].ToString() == "VIEW"))
{
comboBox1.Items.Add((object)info.Rows[x][2].ToString());
}
}
SelectName();
}
private void buttonInsert_Click(object sender, EventArgs e)
{
string name = this.comboBox2.SelectedItem.ToString();
try
{
dbConn = new OleDbConnection();
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
dbConn.Open();
sql = "INSERT INTO " + this.comboBox1.SelectedItem.ToString() + " (Names)" +
"Values (#name)";
OleDbCommand myCommand = new OleDbCommand(sql, dbConn);
myCommand.Parameters.Add("#name", OleDbType.VarChar).Value = name;
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch (Exception err)
{
MessageBox.Show("Error: " + err.Message.ToString());
}
}
private void SelectName()
{
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
try
{
using (dbConn = new OleDbConnection(strCon))
{
dbConn.Open();
sql = "SELECT Name FROM Names";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(sql, dbConn));
DataSet ds = new DataSet();
adapter.Fill(ds, "Names");
comboBox2.Items.Clear();
this.comboBox2.DataSource = ds.Tables["Names"];
this.comboBox2.DisplayMember = "Name";
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString());
}
}
}
}
Try this:
string name = this.comboBox2.Text;

How to take Excel file uploaded from website and import data to SQL Server programmatically?

I'm trying to do something like this:
public void ImportClick(object sender, EventArgs e) //the button used after selecting the spreadsheet file
{
if (fileUpload.HasFile) //ASP.Net FileUpload control
{
if (fileUpload.FileName.EndsWith(".xls", StringComparison.OrdinalIgnoreCase) || fileUpload.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))
{
Excel sheet = new Excel(fileUpload.Open()); //not sure how to do this part
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["our_database"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("INSERT INTO table_name SELECT * FROM " + sheet, connection))
{
connection.Open();
command.ExecuteQuery(); //Intellisense only has "ExecuteNonQuery()" method, but that's for T-SQL
connection.Close();
}
}
}
else
{
error.Text = "File must be either *.xls or *.xlsx";
error.Visible = true;
}
}
else
{
error.Text = "No file was selected";
error.Visible = true;
}
}
There are a lot of classes and interfaces in the Microsoft.Office.Interop.Excel namespace, and I don't know which one to use.
I know making the Excel object, along with the SQL command, probably won't be as easy as what I have here, but those are the two things I need help with.
Any suggestions/advice would be greatly appreciated!
I would suggest using Microsoft Jet Engine.
private static void UploadExcelToDB(string p)
{
try
{
using (SqlConnection conn = new SqlConnection(DBConnString))
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
Log("Opened connection to DB");
}
SqlBulkCopy sbk = new SqlBulkCopy(conn);
sbk.BulkCopyTimeout = 600;
sbk.DestinationTableName = DbTableName;
DataTable excelDT = new DataTable();
OleDbConnection excelConn = new OleDbConnection(ExcelConnString.Replace("xFILEx",p));
excelConn.Open();
if (excelConn.State == ConnectionState.Open)
{
Log("Opened connection to Excel");
}
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.CommandText = "SELECT * FROM ["+ExcelTableName+"]";
cmdExcel.Connection = excelConn;
oda.SelectCommand = cmdExcel;
oda.Fill(excelDT);
if (excelDT != null)
{
Log("Fetched records to local Data Table");
}
excelConn.Close();
SqlCommand sqlCmd = new SqlCommand("TRUNCATE TABLE ICN_NUGGET_REPORT_RAW",conn);
sqlCmd.CommandType = CommandType.Text;
Log("Trying to clear current data in table");
int i = sqlCmd.ExecuteNonQuery();
Log("Table flushed");
Log("Trying write new data to server");
sbk.WriteToServer(excelDT);
Log("Written to server");
conn.Close();
}
}
catch (Exception ex)
{
Log("ERROR: " + ex.Message);
SendErrorReportMail();
}
finally
{
#if (DEBUG)
{
}
#else
{
string archive_file = ArchiveDir+"\\" + DateTime.Now.ToString("yyyyMMdd-Hmmss") + ".xlsx";
File.Move(p, archive_file);
Log("Moved processed file to archive dir");
Log("Starting archive process...");
}
#endif
}
}
This is how ExcelConnString looks like:
public static string ExcelConnString { get { return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=xFILEx;Extended Properties=\"Excel 12.0;HDR=YES\";";} }
HDR=YES - this means that if you have column names in spreadsheet it will be treated as target table column names for matching each other.
I am thinking of creating an instance of excel.application class and writing codes to loop through the cells. And using SQL insert query to copy the rows one by one to the SQL table. I'm still working it out anyway and would paste the code when i'm done.

Categories

Resources