当前位置: 首页 > news >正文

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

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

在这里插入图片描述

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 stringstring 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 statementstring 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);}}
http://www.lryc.cn/news/167187.html

相关文章:

  • js通过xpath定位元素并且操作元素以下拉框select为例
  • 数据类型
  • vue 模板应用
  • Golang教程与Gin教程合集,入门到实战
  • 国家网络安全周 | 天空卫士荣获“2023网络安全优秀创新成果大赛优胜奖”
  • Swift学习笔记一(Array篇)
  • C++项目实战——基于多设计模式下的同步异步日志系统-②-前置知识补充-不定参函数
  • C++使用Boost库加入UDP组播时程序崩溃
  • 华为HCIA(四)
  • Qt --- Day01
  • 24.98万起,新一代AITO问界M7值得买吗?
  • Java毕业设计 SSM SpringBoot 水果蔬菜商城
  • 前端JS中的异步编程与Promise
  • Pytorch Advanced(二) Variational Auto-Encoder
  • Flask 使用 JWT(三)flask-jwt-extended
  • 堆与栈的区别
  • OpenWrt kernel install分析(2)
  • 【计算机网络】传输层协议——TCP(下)
  • Vue前端页面打印
  • Visual Studio将C#项目编译成EXE可执行程序
  • git把某一次commit修改过的文件打包导出(git)
  • Vue3 Ajax(axios)异步
  • idea2023全量方法debug
  • Docker镜像解析获取Dockerfile文件
  • 使用maven命令打jar包
  • 【多线程】死锁 详解
  • 成考[专升本政治]科目必背知识点
  • spring boot 使用AOP+自定义注解+反射实现操作日志记录修改前数据和修改后对比数据,并保存至日志表
  • 【深度学习】Pytorch 系列教程(二):PyTorch数据结构:1、Tensor(张量): GPU加速(GPU Acceleration)
  • 多线程|多进程|高并发网络编程