繁体   English   中英

使用 ClosedXML 示例将数据从 excel 导出到数据库表

[英]Export data from excel to a database table using ClosedXML example

我必须从只有一列的 excel 文件中读取数据行,然后我必须将行保存在数据库的表中。 在我的项目中,我必须使用 ClosedXML .dll 。 我有搜索,但我找不到一个例子。 你能帮我么? 谢谢

对于ClosedXML部分,您可以参考https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data上的文档

private static void Main()
{
  List<String> categories;
  List<String> companies;
  ExtractCategoriesCompanies("NorthwindData.xlsx", out categories, out companies);

  // Do something with the categories and companies
}

private static void ExtractCategoriesCompanies(string northwinddataXlsx, out List<string> categories, out List<string> companies)
{
  categories = new List<string>();
  const int coCategoryId = 1;
  const int coCategoryName = 2;

  var wb = new XLWorkbook(northwinddataXlsx);
  var ws = wb.Worksheet("Data");

  // Look for the first row used
  var firstRowUsed = ws.FirstRowUsed();

  // Narrow down the row so that it only includes the used part
  var categoryRow = firstRowUsed.RowUsed();

  // Move to the next row (it now has the titles)
  categoryRow = categoryRow.RowBelow();

  // Get all categories
  while (!categoryRow.Cell(coCategoryId).IsEmpty())
  {
    String categoryName = categoryRow.Cell(coCategoryName).GetString();
    categories.Add(categoryName);

    categoryRow = categoryRow.RowBelow();
  }

  // There are many ways to get the company table.
  // Here we're using a straightforward method.
  // Another way would be to find the first row in the company table
  // by looping while row.IsEmpty()

  // First possible address of the company table:
  var firstPossibleAddress = ws.Row(categoryRow.RowNumber()).FirstCell().Address;
  // Last possible address of the company table:
  var lastPossibleAddress = ws.LastCellUsed().Address;

  // Get a range with the remainder of the worksheet data (the range used)
  var companyRange = ws.Range(firstPossibleAddress, lastPossibleAddress).RangeUsed();

  // Treat the range as a table (to be able to use the column names)
  var companyTable = companyRange.AsTable();

  // Get the list of company names
  companies = companyTable.DataRange.Rows()
    .Select(companyRow => companyRow.Field("Company Name").GetString())
    .ToList();
}

编辑:下面只为您提供一个填充的数据表。 然后您需要将该数据表加载到您的数据库中。 您没有说这是哪个数据库,但对于 SQL Server,您将使用SqlBulkCopy类(参见定义,其中也有一个示例)。

聚会迟到了,但试试这个:

public static DataTable GetDataTableFromExcel(string path, string sheetname = "", bool hasHeader = true)
{
  using (var workbook = new XLWorkbook(path))
  {
    IXLWorksheet worksheet;
    if (string.IsNullOrEmpty(sheetname))
      worksheet = workbook.Worksheets.First();
    else
      worksheet = workbook.Worksheets.FirstOrDefault(x => x.Name == sheetname);

    var rangeRowFirst = worksheet.FirstRowUsed().RowNumber();
    var rangeRowLast = worksheet.LastRowUsed().RowNumber();
    var rangeColFirst = worksheet.FirstColumnUsed().ColumnNumber();
    var rangeColLast = worksheet.LastColumnUsed().ColumnNumber();

    DataTable tbl = new DataTable();

    for (int col = rangeColFirst; col <= rangeColLast; col++)
      tbl.Columns.Add(hasHeader ? worksheet.FirstRowUsed().Cell(col).Value.ToString() : $"Column {col}");

    Logger("started creating datatable");

    rangeRowFirst = rangeRowFirst + (hasHeader ? 1 : 0);
    var colCount = rangeColLast - rangeColFirst;
    for (int rowNum = rangeRowFirst; rowNum <= rangeRowLast; rowNum++)
    {
      List<string> colValues = new List<string>();
      for (int col = 1; col <= colCount; col++)
      {
        colValues.Add(worksheet.Row(rowNum).Cell(col).Value.ToString());
      }
      tbl.Rows.Add(colValues.ToArray());
    }

    Logger("finished creating datatable");
    return tbl;
  }
}

并像这样调用:

var datatable = GetDataTableFromExcel(fileName, sheetName);

如果你使用(其基本形式的优秀且免费的) LinqPad ,您可以检查datatable使用datatable.Dump();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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