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);
            }
        }
相关推荐
养生技术人11 小时前
Oracle OCP认证考试题目详解082系列第57题
运维·数据库·sql·oracle·开闭原则
不良人天码星11 小时前
redis-zset数据类型的常见指令(sorted set)
数据库·redis·缓存
心灵宝贝11 小时前
libopenssl-1_0_0-devel-1.0.2p RPM 包安装教程(openSUSE/SLES x86_64)
linux·服务器·数据库
张人玉13 小时前
C# 通讯关键类的API
开发语言·c#
程序新视界13 小时前
MySQL中,IS NULL和IS NOT NULL不会走索引?错!
数据库·mysql·dba
wdfk_prog13 小时前
闹钟定时器(Alarm Timer)初始化:构建可挂起的定时器基础框架
java·linux·数据库
芭拉拉小魔仙13 小时前
Vue项目中如何实现表格选中数据的 Excel 导出
前端·vue.js·excel
RE-190113 小时前
Excel基础知识 - 导图笔记
数据分析·学习笔记·excel·思维导图·基础知识·函数应用
许长安13 小时前
Redis(二)——Redis协议与异步方式
数据库·redis·junit
java_python源码14 小时前
python高校心理健康服务小程序(源码+文档+调试+基础修改+答疑)
数据库·sqlite