If in SQL we created a table with 10 columns with column names col1 col2...col10.Now we take any Excel that has data in 10 columns, but the column name is different.
how do I do this? What I'm saying is that I will create a table in SQL only once, and in that table, I should save any Excel data, even though the column names are different. I hope you understand .Thanks in advance

Amit MohantyRank #112 · 20K reputationPosted May 15, 2024, 7:32 AM EDT
Check the below example, this may help you.
using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using OfficeOpenXml; using ExcelWorksheet = OfficeOpenXml.ExcelWorksheet; using LicenseContext = OfficeOpenXml.LicenseContext; namespace ExcelToSql { public class ExcelProcessor { public void SaveExcelDataToSql(string excelFilePath, string connectionString, string tableName) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var package = new ExcelPackage(new FileInfo(excelFilePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) { Console.WriteLine("No worksheet found in the Excel file."); return; } string insertQuery = $"INSERT INTO {tableName} VALUES "; for (int row = 2; row worksheet.Cells[row, col].Value != null ? worksheet.Cells[row, col].Value.ToString() : "") .ToArray(); string rowValueString = $"('{string.Join("','", rowValues)}')"; insertQuery += rowValueString + ","; } insertQuery = insertQuery.TrimEnd(',') + ";"; using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var command = new SqlCommand(insertQuery, connection)) { command.ExecuteNonQuery(); } } } } } }