我想将Excel工作表的内容读入C#DataTable。 Excel工作表可以包含可变数量的列和行。 Excel工作表中的第一行将始终包含列名称,但其他行可能为空。
我在这里看到的所有建议都假设存在Microsoft.ACE.OLEDB
。我没有在我的系统上安装此库,因为当我尝试其中一些解决方案时,我收到此错误。
Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
考虑到我安装了Office 2016,这很奇怪。
出于这个原因,我希望通过Nuget使用ClosedXML库,但我没有在他们的维基中看到任何用C#读取Excel工作表到DataTable的例子。
这个例子不是我的。我不记得我从哪里得到它,因为它在我的档案中。但是,这对我有用。我遇到的唯一问题是空白单元格。根据dicussion on the ClosedXML GitHUb wiki page,它与Excel有关,不跟踪不受数据限制的空单元格。我发现如果我将数据添加到单元格然后删除相同的数据,则该过程有效。
public static DataTable ImportExceltoDatatable(string filePath, string sheetName)
{
// Open the Excel file using ClosedXML.
// Keep in mind the Excel file cannot be open when trying to read it
using (XLWorkbook workBook = new XLWorkbook(filePath))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(1);
//Create a new DataTable.
DataTable dt = new DataTable();
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
firstRow = false;
}
else
{
//Add rows to DataTable.
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells(row.FirstCellUsed().Address.ColumnNumber, row.LastCellUsed().Address.ColumnNumber))
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
}
return dt;
}
}
需要补充
using System.Data;
using ClosedXML.Excel;
以及ClosedXML nuget包
对于其他日期时间数据类型...这可能会有所帮助... reference
if (cell.Address.ColumnLetter=="J") // Column with date datatype
{
DateTime dtime = DateTime.FromOADate(double.Parse(cell.Value.ToString()));
dt.Rows[dt.Rows.Count - 1][i] = dtime;
}
else
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
}
使用此代码,您可以阅读Excel工作表的内容。您可以指定工作表的名称或编号,将返回包含工作表内容的数据集。
public static DataTable GetDataFromExcel(string path, dynamic worksheet)
{
//Save the uploaded Excel file.
DataTable dt = new DataTable();
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(path))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(worksheet);
//Create a new DataTable.
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
if (!string.IsNullOrEmpty(cell.Value.ToString()))
{
dt.Columns.Add(cell.Value.ToString());
}
else
{
break;
}
}
firstRow = false;
}
else
{
int i = 0;
DataRow toInsert = dt.NewRow();
foreach (IXLCell cell in row.Cells(1, dt.Columns.Count))
{
try
{
toInsert[i] = cell.Value.ToString();
}
catch (Exception ex)
{
}
i++;
}
dt.Rows.Add(toInsert);
}
}
return dt;
}