excel - 使用 ClosedXML 将 Excel 工作表读入 DataTable

标签 excel datatable closedxml

我想将 Excel 工作表的内容读入 C# DataTable。 Excel 工作表可以有可变数量的列和行。 Excel 工作表中的第一行将始终包含列名,但其他行可能为空白。

我在 SO 中看到的所有建议都假设存在 Microsoft.ACE.OLEDB .我的系统上没有安装这个库,因为当我尝试其中一些解决方案时,我得到了这个错误。

Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

奇怪的是我安装了 Office 2016。

出于这个原因,我希望通过 Nuget 使用 ClosedXML 库,但我在他们的 wiki 中没有看到任何将 Excel 工作表读取到 C# 中的 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 - 使用 ClosedXML 将 Excel 工作表读入 DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48756449/

相关文章:

SQL 浮点精度限制为 6 位

excel - 如何在vba中另存为.txt

r - 将 R 列值扩展为具有另一列值的列标题

c# - 列不允许 DBNull.Value - 没有 KeepNulls - 正确的列映射

c# - 如何从 excel 单元格中获取完整值,而不是显示的(四舍五入的)值?

java - OOXML 电子表格中的默认单元格类型

vba - Excel:每x秒重新计算一次

c# - 在特定条件下从两个数据表中构建一个

.net - ClosedXML - 无法加载文件或程序集

c# - 使用 ClosedXML 从 Excel 文件中读取