简体   繁体   中英

How to import multiple Excel sheets into SQL tables using C#?

我需要通过单击 C# 按钮控件将多个 Excel 工作表导入多个 SQL 表(根据它们的表)。

at frist please install nuget Spire.XLS for example 'Install-Package Spire.XLS -Version 9.6.7' now you can use code below
you should using Spire.xls in your namespace

 public static DataTable ReadExcelFromPath(string path,int sheetNumber)
    {
        DataTable dt = null;
        try
        {
            //Load the Excel file
            using (Workbook workbook = new Workbook())
            {
                workbook.LoadFromFile(path);

                //Get the  worksheet
                Worksheet sheet = workbook.Worksheets[sheetNumber];
                //Export data to data table
                dt = sheet.ExportDataTable();

            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());

        }
        return dt;
    }


 public static List<DataTable> ReadAllExcelSheetFromPath(string path)
    {
        List<DataTable> dt_list = new List<DataTable>();
        try
        {
            //Load the Excel file
            using (Workbook workbook = new Workbook())
            {
                workbook.LoadFromFile(path);
                for (int i = 0; i < workbook.Worksheets.Count; i++)
                { //Get the first worksheet
                    Worksheet sheet = workbook.Worksheets[i];
                    //Export data to data table
                    dt_list.Add( sheet.ExportDataTable());
                }

            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());

        }
        return dt_list;
    }

Use EPPlus nuget package.

Documentation link: https://github.com/JanKallman/EPPlus/wiki/Reading-and-Writing-Data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM