[英]How to import multiple Excel sheets into SQL tables using C#?
我需要通过单击 C# 按钮控件将多个 Excel 工作表导入多个 SQL 表(根据它们的表)。
首先请安装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;
}
使用EPPlus nuget 包。
文档链接: https : //github.com/JanKallman/EPPlus/wiki/Reading-and-Writing-Data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.