C#根据excel文件中的表头创建数据库表

C#根据excel文件中的表头创建数据库表

csharp 复制代码
private void button1_Click(object sender, EventArgs e)
        {
            
            string tableName = tableNameTextBox.Text;
            string connectionString = "";

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Excel Files|*.xlsx;*.xls";
                openFileDialog.Title = "Select an Excel file";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName;
                    tableName = tableNameTextBox.Text;
                    connectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath}; Extended Properties='Excel 12.0;HDR=YES;'";
                }
            }
            // SQL Server connection string
            string sqlConnectionString = "server=127.0.0.1;uid=sa;pwd=xyz@1230;database="+ datebasetext.Text;

            try
            {
                using (OleDbConnection excelConnection = new OleDbConnection(connectionString))
                {
                    excelConnection.Open();
                    DataTable schemaTable = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);

                    if (schemaTable.Rows.Count == 0)
                    {
                        MessageBox.Show("Excel文件列名为空!");
                        return;
                    }
                    DataView sortedView = schemaTable.DefaultView;
                    sortedView.Sort = "ORDINAL_POSITION ASC";
                    DataTable sortedSchemaTable = sortedView.ToTable();

                    // Create the SQL CREATE TABLE statement
                    string createTableQuery = $"CREATE TABLE {tableName} (";

                    List<string> existingColumnNames = new List<string>();

                    foreach (DataRow row in sortedSchemaTable.Rows)
                    {
                        string columnName = row["COLUMN_NAME"].ToString();
                        if (!existingColumnNames.Contains(columnName))
                        {
                            createTableQuery += $"[{columnName}] NVARCHAR(200), ";
                            existingColumnNames.Add(columnName);
                        }
                    }
                    createTableQuery = createTableQuery.TrimEnd(',', ' ');
                    createTableQuery += ")";
                    using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
                    {
                        sqlConnection.Open();
                        using (SqlCommand sqlCommand = new SqlCommand(createTableQuery, sqlConnection))
                        {
                            sqlCommand.ExecuteNonQuery();
                        }
                    }
                    MessageBox.Show("创建表成功!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("报错信息: " + ex.Message);
            }
        }
相关推荐
Eiceblue3 分钟前
C# 实现 XLS 与 XLSX 格式双向互转(无需依赖 Office)
开发语言·c#·visual studio
识君啊3 分钟前
中小厂数据库事务高频面试题
java·数据库·mysql·隔离级别·数据库事务·acid
2301_816660217 分钟前
Bootstrap框架的最小宽度限制是多少
jvm·数据库·python
OtIo TALL12 分钟前
SQL-触发器(trigger)的详解以及代码演示
服务器·数据库·sql
lwx5728015 分钟前
MySQL 数据库自动化备份脚本:从入门到生产实践
数据库·后端
abc123456sdggfd33 分钟前
HTML5中Vuex持久化插件中WebStorage的底层配置
jvm·数据库·python
pele36 分钟前
Go语言如何发GET请求_Go语言HTTP GET请求教程【总结】
jvm·数据库·python
weixin_5806140036 分钟前
Go 语言中 go install 命令的正确用法与常见误区详解
jvm·数据库·python
qq_6543669837 分钟前
Bootstrap 5移除jQuery依赖 Bootstrap 5如何不使用jQuery
jvm·数据库·python