如何使用C#将多个Excel工作表导入SQL表?

时间:2019-06-19 11:34:30

标签: c# sql excel datatable

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

请帮助我

2 个答案:

答案 0 :(得分:0)

请首先安装nuget Spire.XLS,例如'Install-Package Spire.XLS -Version 9.6.7'  现在您可以使用下面的代码了
   你应该         使用Spire.xls   在您的命名空间中

 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;
    }

答案 1 :(得分:-2)

使用 EPPlus nuget程序包。

文档链接: https://github.com/JanKallman/EPPlus/wiki/Reading-and-Writing-Data