如何从excel中获取唯一的列数据在c#中的数据库表列中

我有一个具有特定列标题的150列的Excel文件。 在我的数据库中,有一个“ ExcelImport ”表, ExcelHead列(包含与Excel列标题名称相同的列标题数据)。

create table ExcelImport( id int primary key,ExcelHead varchar(max)) insert into ExcelImport values(1,'Role'),(2,'Manager') 

这个表格将获得基于另一个规则的数据。 我的要求是,我需要从excel中取出ExcelImport表中的唯一列数据并插入到另一个临时表中。 从这个例子我需要只提取'angular色'和'经理'Excel列,需要插入到临时表。

注意 :每次ExcelImport表格数据都将被截断,ExcelHead的新值将被插入。

任何人可以build议做同样的编码?

首先你必须从你的excel文件中读取你的列标题。 试着在这里看看,以了解如何从Excel文件中读取列标题。 列标题通常是excel文件的第一行,所以如果你只是读取列标题的excel文件的第一行就可以了。 我通常会使用一个Dictionary来跟踪列标题和列索引。 然后,您需要使用sql来查询ExcelImport表以获取您想要用作filter的所有列名称。 我将交叉引用两个数据(ExcelImport和Dictionary)来获取需要获取的excel文件的所有行索引。然后迭代所有行以获取excel文件的所有数据。最后,我将删除所有来自ExcelImport的数据并将新数据插入到ExcelImport表中。 你可以看看下面的伪代码。

  public Dictionary<string,int> GetDictionary(string fullExcelPath) { //Dictionary<Column Header,Column Index> Dictionary<string,int> columns=new Dictionary<string,int>(); ExcelWorkbook excelWorkbook = ExcelWorkbook.ReadXLSX(fullExcelPath); ExcelWorksheet excelWorkSheet = excelWorkbook.Worksheets[0]; DataTable dataTable = excelWorkSheet.WriteToDataTable(); DataTable columns=dataTable.Rows[0]; //iterate to get the column header for(int i=0;;i++) { string header=(string )row[i]; if(!string.IsNullOrWhiteSpace(header)) { columns.Add(header,i); } else { break; } } return columns; } public void DoWork() { Dictionary<string,int> columnsFromExcel=GetDictionary(excelPath); List<string> columnToFilter=GetFromDatabase(); int[] columnIndex=CrossReferenceData(columnsFromExcel,columnToFilter); //column index=index we wanted to get data from //GetDataFromExcel =basically same as GetDictionary but it read from //second row instead of first row and used columnIndex to get data from //dataTable (look GetDictionary method). List<string> dataFromExcel=GetDataFromExcel(columnIndex); DeleteExcelImportTable(); // dynamically created your insert sql string insertSQL=GetInsertSQL(dataFromExcel); InsertExcelImportTable(insertSQL); } 
  DataSet ExcelDataset = DBcom.GetDataset(); //add logic for getting excel imported data in dataset format. string[] columnsNames = new string[100]; int loop = 0; //Comparing the Imported Excel Column With Database Table Column foreach (DataColumn column in ExcelDataset.Tables[0].Columns) { string clnameExcel = column.ColumnName; int Exist = 0; foreach (DataTable table in DataBaseDataset.Tables) { foreach (DataRow dr in table.Rows) { string ColnamesDB = dr["DBColumn"].ToString();//DBColumn is the name of database table column name if (CompclnameExcel == CompColnamesDB) { Exist = 1; break; } } } if (Exist == 0) { columnsNames[loop] = clnameExcel; loop++; } } //Deleting Imported Excel Columns which is not there in Database foreach (string cNames in columnsNames) { if (!string.IsNullOrEmpty(cNames)) { ExcelDataset.Tables[0].Columns.Remove(cNames); } }