简体   繁体   English

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

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

i have to read rows of data from an excel file which has only a column and then i have to save the rows in a table in database .我必须从只有一列的 excel 文件中读取数据行,然后我必须将行保存在数据库的表中。 In my project i have to use ClosedXML .dll .在我的项目中,我必须使用 ClosedXML .dll 。 I have search but i couldn't find an example .我有搜索,但我找不到一个例子。 Can you please help me?你能帮我么? Thanks谢谢

For the ClosedXML part, you can refer to the documentation at https://github.com/ClosedXML/ClosedXML/wiki/Finding-and-extracting-the-data对于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();
}

EDIT: The below only gets you a populated datatable.编辑:下面只为您提供一个填充的数据表。 You'll then need to load that datatable into your database.然后您需要将该数据表加载到您的数据库中。 You don't say which database this is, but for SQL Server you would use the SqlBulkCopy class (see definition , which also has an example).您没有说这是哪个数据库,但对于 SQL Server,您将使用SqlBulkCopy类(参见定义,其中也有一个示例)。

Late to the party, but try this:聚会迟到了,但试试这个:

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

and call like this:并像这样调用:

var datatable = GetDataTableFromExcel(fileName, sheetName);

If you're using (the excellent and free in its basic form) LinqPad , you can inspect the datatable using datatable.Dump();如果你使用(其基本形式的优秀且免费的) LinqPad ,您可以检查datatable使用datatable.Dump();

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

相关问题 如何使用Spring MVC将数据从数据库导出到Excel工作表? - How to export data from database to excel sheet using spring MVC? 使用 spring 将数据从数据库导出到 xlsx 文件(Excel) - Export data from database to xlsx file (Excel) using spring 如何将foxpro数据库中的数据导出为ex​​cel(.xls)? - How can I export data from a foxpro database to excel(.xls)? 将数据从Excel文件导出到SQL Server数据库的最佳方法 - Best way to export data from an Excel file to SQL server database 如何通过功能将来自数据库的数据导出到Excel - How To Export Data That Coming From DataBase Via Function to Excel 如何在C#中使用LINQ将数据从Gridview或数据库导出到Excel? - How to export data from Gridview or Database to Excel with LINQ in C#? 经典的ASP代码将数据从Access数据库导出到Excel工作表 - Classic asp code to export data from Access database to an Excel sheet 数据库导出-导入中的垃圾数据使用相同的表排序规则 - Garbage data in database export-import using the same table collation 如何将记录/数据从一个数据库表导出到另一个数据库表? - how to export records/data from one database table to another database table? 将数据库从Progress Software(1998)导出到Excel - Export database from Progress Software (1998) to Excel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM