How to store data from Excel to database?

Majeed Purseyedmahdi 41 Reputation points
2024-03-02T07:36:41.3933333+00:00

How to store data from Excel to database in EF C# windows form Application?

Developer technologies Windows Forms
Developer technologies .NET Other
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2024-03-02T10:12:44.7066667+00:00

    I put together a simple example using ExcelMapper NuGet package which takes a model and reads data from a specific WorkSheet into a SQL-Server database table via EF Core 8 in a console project and will work in any project type. Note code written with .NET Core 8.

    You of course will need to create a class to match your data as I did for my code sample.

    Find a working code sample in this project in a GitHub repository.

    internal partial class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                const string excelFile = "Customers.xlsx";
                var excel = new ExcelMapper();
                var customers = (await excel.FetchAsync<Customers>(excelFile,"Customers")).ToList();
                await using var context = new Context();
                context.Customers.AddRange(customers);
                var affected = await context.SaveChangesAsync();
                Console.WriteLine(affected > 0 ? $"Saved {affected} records" : "Failed");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
    
            Console.ReadLine();
        }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.