6

I want to upload a excel file through windows form application in c# and want to import the data to database ( Mysql server). how can i do that??? I have created a form which requires me to upload a excel file into the mysql database . its an bulk insert data to database table.

My Excel File Contain columns like userid,password,first_name,last_name,user_group AND MySql Database table(aster_users) Contain many columns like userid,password,first_name,last_name,user_group,queue,active,created_date,created_by,role ..

i need to upload that excel file to my database and other columns will get empty or null that's not a matter.

My Form design is enter image description here

Here is My c# Code:

using MySql.Data.MySqlClient;
using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace UploadFileToDatabase
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();       
    }

    String MyConString = "SERVER=******;" +
           "DATABASE=dbs;" +
           "UID=root;" +
           "PASSWORD=pwsd;" + "Convert Zero Datetime = True";
private void BtnSelectFile_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "Text files | *.csv";
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            string fileName;
            fileName = dlg.FileName;
            txtfilepath.Text = fileName;
        }
      }

private void btnUpload_Click(object sender, EventArgs e)           
 {                
    string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtfileparth.Text + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";

        using (OleDbConnection connection =
              new OleDbConnection(connectionString))
        {
            OleDbCommand command = new OleDbCommand
                    ("Select * FROM [Sheet1$]", connection);

            connection.Open();

            using (DbDataReader dr = command.ExecuteReader())
            {
                string sqlConnectionString = MyConString;

                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
                {
                    bulkCopy.ColumnMappings.Add("[userid]", "userid");
                    bulkCopy.ColumnMappings.Add("password", "password");
                    bulkCopy.ColumnMappings.Add("first_name", "first_name");
                    bulkCopy.ColumnMappings.Add("last_name", "last_name");
                    bulkCopy.ColumnMappings.Add("user_group", "user_group");
                    bulkCopy.DestinationTableName = "aster_users";
                    bulkCopy.WriteToServer(dr);
                    MessageBox.Show("Upload Successfull!");
                }
            }

        }
}

Here is how i tried.i got an error message like this

Additional information: External table is not in the expected format.

in this line connection.Open(); . How can this be Done?

5 Answers 5

6

enter image description here

using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace IMPORT
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    String MyConString = "SERVER=******;" +
           "DATABASE=db;" +
           "UID=root;" +
           "PASSWORD=pws;";

private void btnSelectFile_Click(object sender, EventArgs e)
    {
        OpenFileDialog openfiledialog1 = new OpenFileDialog();
        openfiledialog1.ShowDialog();
        openfiledialog1.Filter = "allfiles|*.xls";
        txtfilepath.Text = openfiledialog1.FileName;
    }
private void btnUpload_Click(object sender, EventArgs e)
{
 string path = txtfilepath.Text;

        string ConnString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties = Excel 8.0";

        DataTable Data = new DataTable();

        using (OleDbConnection conn =new OleDbConnection(ConnString))
        {
            conn.Open();

            OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM [dataGridView1_Data$]", conn);
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            adapter.Fill(Data);

            conn.Close();
        }
        string ConnStr = MyConString;
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr))
        {
            bulkCopy.DestinationTableName = "TABLE NAME";
            bulkCopy.ColumnMappings.Add("userid", "userid");
            bulkCopy.ColumnMappings.Add("password", "password");
            bulkCopy.ColumnMappings.Add("first_name", "first_name");
            bulkCopy.ColumnMappings.Add("last_name", "last_name");
            bulkCopy.ColumnMappings.Add("user_group", "user_group");
            bulkCopy.WriteToServer(Data);
            MessageBox.Show("UPLOAD SUCCESSFULLY");
        }
     }
 }

An example found http://technico.qnownow.com/bulk-copy-data-from-excel-to-destination-db-using-sql-bulk-copy/. And ERROR: Additional information: External table is not in the expected format

Sign up to request clarification or add additional context in comments.

Comments

2
+100

ஆர்த்தி,

Use the Below Connection String Format

 string File = sResponsedExcelFilePath;

 string result = Path.GetFileName(sFilePath);    

 ExcelReaderConnString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + File +"\\"+ result + ";Extended Properties=Excel 12.0;");

Hope this works for you.

2 Comments

sorry for inconvenient . while running the program i got an error as (Additional information: The Microsoft Office Access database engine cannot open or write to the file 'C:\'. It is already opened exclusively by another user, or you need permission to view and write its data) . sorry for trouble.
Please place the file in other drive except C:. Close the Excel file if its opening.
2

There is an awesome link that shows how to upload to c# datatable from excel...in case the link dies I am sharing the procedure....

The excel Connection Strings for diff versions:

private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";

The File select event:

private void BtnSelectFile_Click(object sender, EventArgs e)
    {
        DataTable dt;
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "Excel files | *.xls";
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            string filePath = dlg.FileName;
            string extension = Path.GetExtension(filePath);
            string conStr, sheetName;

            conStr = string.Empty;
            switch (extension)
            {

                case ".xls": //Excel 97-03
                    conStr = string.Format(Excel03ConString, filePath);
                    break;

                case ".xlsx": //Excel 07 to later
                    conStr = string.Format(Excel07ConString, filePath);
                    break;
            }

            //Read Data from the Sheet.
            using (OleDbConnection con = new OleDbConnection(conStr))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    using (OleDbDataAdapter oda = new OleDbDataAdapter())
                    {
                        dt = new DataTable();
                        cmd.CommandText = "SELECT * From [Sheet1$]";
                        cmd.Connection = con;
                        con.Open();
                        oda.SelectCommand = cmd;
                        oda.Fill(dt);
                        con.Close();
                    }
                }
            }
            //Save the datatable to Database
            string sqlConnectionString = MyConString;
            if(dt != null)
            {                
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
            {
                bulkCopy.ColumnMappings.Add("[userid]", "userid");
                bulkCopy.ColumnMappings.Add("password", "password");
                bulkCopy.ColumnMappings.Add("first_name", "first_name");
                bulkCopy.ColumnMappings.Add("last_name", "last_name");
                bulkCopy.ColumnMappings.Add("user_group", "user_group");
                bulkCopy.DestinationTableName = "aster_users";
                bulkCopy.WriteToServer(dt);
                MessageBox.Show("Upload Successfull!");
            }
            }
        }
}

Then you can just save the datatable to mySql database which I hope you know how to do...If you can't then comment I'll try my best to help you. Thank You

Hope this helps....

4 Comments

@ khaled4vokalz . Thank you for your answer.I tried this but i didn't get my output. here my problem is that when i click choose file button i get open my file dialogBox and select my file which contain data to import it in my Database table . The file path is shown in my textbox and when i click upload button the file need to upload on database.
yes sir please me please got an error like this Additional information: External table is not in the expected format. . still i am searching for an answer.
@Arthi I have posted answer check it out.
Alhamdulillah....If that helped you then please mark that as an answer... Thank You.... @Arthi
1
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace IMPORT
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    String MyConString = "SERVER=******;" +
           "DATABASE=db;" +
           "UID=root;" +
           "PASSWORD=pws;";

private void btnSelectFile_Click(object sender, EventArgs e)
    {
        OpenFileDialog openfiledialog1 = new OpenFileDialog();
        openfiledialog1.ShowDialog();
        openfiledialog1.Filter = "allfiles|*.xls";
        txtfilepath.Text = openfiledialog1.FileName;
    }
private void btnUpload_Click(object sender, EventArgs e)
{
 string path = txtfilepath.Text;

        string ConnString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties = Excel 8.0";

        DataTable Data = new DataTable();

        using (OleDbConnection conn =new OleDbConnection(ConnString))
        {
            conn.Open();

            OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM [dataGridView1_Data$]", conn);
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            adapter.Fill(Data);

            conn.Close();
        }
        string ConnStr = MyConString;
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr))
        {
            bulkCopy.DestinationTableName = "TABLE NAME";
            bulkCopy.ColumnMappings.Add("userid", "userid");
            bulkCopy.ColumnMappings.Add("password", "password");
            bulkCopy.ColumnMappings.Add("first_name", "first_name");
            bulkCopy.ColumnMappings.Add("last_name", "last_name");
            bulkCopy.ColumnMappings.Add("user_group", "user_group");
            bulkCopy.WriteToServer(Data);
            MessageBox.Show("UPLOAD SUCCESSFULLY");
        }
     }
 }

Comments

0

I had huge problems trying to use either/both Jet and ACE.OLEDB providers. You could try this o/s library ClosedXML, which will import xlsx files: 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

Available via Nuget. It has its own wiki: https://github.com/ClosedXML/ClosedXML/wiki

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.