如果excel列和SQL表列相等,则上传上传 [英] Acepting the upload if excel columns and SQL table columns are equal

查看:45
本文介绍了如果excel列和SQL表列相等,则上传上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有列名的SQL表,没有数据。我有另一个包含列名和数据的excel表。我需要将数据从excel导入到sql表中。在此之前,我需要比较sql列名称和excel列名称。如果可以,那么只需要导入。





请帮我清楚编码。 c#中的代码

I have a SQL table with column name and no data. i have another excel sheet with column name and data. i need to import the data from excel to sql table. Before that i need to compare sql column names and excel column names. if thats ok then only it needs to be imported.


Please Help me with clear coding. code in c#

推荐答案

使用此通用代码验证带有数据库表列的Excel列



Use this Generic Code for Validating the Excel columns with the Database table Columns

private static bool IsColumnsEqual(DataTable excel, SqlConnection con, string tableName)
      {
          SqlCommand cmd = new SqlCommand("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @tableName", con);
          cmd.Parameters.AddWithValue("@tableName", tableName);
          SqlDataAdapter da = new SqlDataAdapter(cmd);
          DataTable dtColumns = new DataTable();
          da.Fill(dtColumns);
          List<string> lstColumnNames = new List<string>();
          foreach (DataRow row in dtColumns.Rows)
              lstColumnNames.Add(row["COLUMN_NAME"].ToString());

          string[] excelColumnNames = excel.Columns.OfType<DataColumn>().Select(k => k.ColumnName).ToArray();
          bool equals = excelColumnNames.Intersect(lstColumnNames).Count() == excelColumnNames.Union(lstColumnNames).Count();
          return equals;

      }





用法:



Usage:

bool isEqual = IsColumnsEqual(dtExcel, con, "Your_Table_Name");
          if (isEqual) {
              // do upload
          }


这篇关于如果excel列和SQL表列相等,则上传上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆