如何使用c#windows form应用程序将excel文件上传到sql数据库表

时间:2015-12-12 10:16:35

标签: c# mysql database excel

我想通过c#中的windows表单应用程序上传excel文件,并希望将数据导入数据库(Mysql服务器)。我怎样才能做到这一点???我创建了一个表单,要求我将excel文件上传到mysql数据库。它是一个批量插入数据到数据库表。

我的Excel文件包含userid,password,first_name,last_name,user_group AND等列 MySql数据库表(aster_users)包含许多列,如userid,password,first_name,last_name,user_group,queue,active,created_date,created_by,role ..

我需要将该excel文件上传到我的数据库,其他列将变为空或null,这不是问题。

我的表单设计是 enter image description here

这是我的c#代码:

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!");
                }
            }

        }
}

以下是我试过的方法。我收到了这样的错误信息

  

附加信息:外部表格不符合预期格式。

在此行 connection.Open(); 。怎么能完成呢?

5 个答案:

答案 0 :(得分:5)

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");
        }
     }
 }

找到了一个示例 http://technico.qnownow.com/bulk-copy-data-from-excel-to-destination-db-using-sql-bulk-copy/ ERROR: Additional information: External table is not in the expected format

答案 1 :(得分:2)

有一个awesome link显示如何从excel上传到c#datatable ...如果链接死亡我正在共享该过程....

excel版本的连接字符串:

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'";

文件选择事件:

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!");
            }
            }
        }
}

然后您可以将数据表保存到mySql数据库,我希望您知道该怎么做...如果您不能发表评论,我会尽力帮助您。谢谢

希望这会有所帮助......

答案 2 :(得分:2)

ஆர்த்தி,

使用以下连接字符串格式

 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;");

希望这适合你。

答案 3 :(得分: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");
        }
     }
 }

答案 4 :(得分:0)

我在尝试使用Jet和ACE.OLEDB提供程序时遇到了很大的问题。您可以尝试使用此o / s库ClosedXML,该库将导入xlsx文件:'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

可通过Nuget获得。它有自己的Wiki:https://github.com/ClosedXML/ClosedXML/wiki