简体   繁体   English

如何从 XLSX (Excel) 读取?

[英]How to read from XLSX (Excel)?

I have a problem with reading from .xlsx (Excel) file.我在读取 .xlsx (Excel) 文件时遇到问题。 I tried to use:我尝试使用:

var fileName = @"C:\automated_testing\ProductsUploadTemplate-2015-10-22.xlsx";
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "XLSData");
DataTable data = ds.Tables["XLSData"];

// ... Loop over all rows.
StringBuilder sb = new StringBuilder();
foreach (DataRow row in data.Rows)
{
    sb.AppendLine(string.Join(",", row.ItemArray));
}

but if failed due to connectionString .但如果由于connectionString失败。 So I updated the line to support .xlsx:所以我更新了该行以支持 .xlsx:

var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", fileName);

but I get:但我得到:

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. “Microsoft.ACE.OLEDB.12.0”提供程序未在本地计算机上注册。

(Problem here is that, I am not able to install new software on my remote-testing machine, so I am not able to fix it and need to find other solution.) (这里的问题是,我无法在我的远程测试机器上安装新软件,所以我无法修复它,需要找到其他解决方案。)

I do also need to be sure that imported data will be stored in some simple way (I am beginner programmer) to let me iterate through it ie to create objects with row's data.我还需要确保导入的数据将以某种简单的方式存储(我是初级程序员),以便我遍历它,即使用行数据创建对象。

Other approaches I checked:我检查过的其他方法:

comment: seems to probably work for me, but doesn't support Excel files of unknown dimensions (random number of rows and columns).评论:似乎可能对我有用,但不支持未知维度的 Excel 文件(行和列的随机数)。

comment: doesn't support settings column names from different row than first one (in some of my Excel files, there are comments in 4-6 first rows and then is headers row and data below).评论:不支持设置与第一行不同的列名(在我的某些 Excel 文件中,第一行有 4-6 行评论,然后是标题行和下面的数据)。

comment: same problem as above.评论:与上述相同的问题。

comment: downloaded package weight was over 60MB and it requires me to install it on system, which is not possible in my situation.评论:下载的包重量超过 60MB,它需要我在系统上安装它,这在我的情况下是不可能的。 Anyway, people comment that it is limited to 150 rows.无论如何,人们评论说它仅限于 150 行。

Meanwhile I will try to check https://code.google.com/p/linqtoexcel/ , but all other ideas are more than welcome!同时我会尝试检查https://code.google.com/p/linqtoexcel/ ,但所有其他想法都非常受欢迎!

EDIT: Just checked that LinqToExcel, same issue as above:编辑:刚刚检查了 LinqToExcel,与上述相同的问题:

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. “Microsoft.ACE.OLEDB.12.0”提供程序未在本地计算机上注册。

EDIT2: Ultimately, it seems that this solution solved my issue: EDIT2:最终,这个解决方案似乎解决了我的问题:

https://stackoverflow.com/a/19065266/3146582 https://stackoverflow.com/a/19065266/3146582

If you are reading data from Excel file, you can use EPPlus NuGet package, and use following code:如果您从Excel文件中读取数据,您可以使用EPPlus NuGet 包,并使用以下代码:

//using OfficeOpenXml;
using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(@"C:\YourDirectory\sample.xlsx")))
{
    var myWorksheet = xlPackage.Workbook.Worksheets.First(); //select sheet here
    var totalRows = myWorksheet.Dimension.End.Row;
    var totalColumns = myWorksheet.Dimension.End.Column;

    var sb = new StringBuilder(); //this is your data
    for (int rowNum = 1; rowNum <= totalRows; rowNum++) //select starting row here
    {
        var row = myWorksheet.Cells[rowNum, 1, rowNum, totalColumns].Select(c => c.Value == null ? string.Empty : c.Value.ToString());
        sb.AppendLine(string.Join(",", row));
    }
}

Reading Excel files with OLE provider is possible only if MS Jet engine (MS Access) is installed.仅当安装了 MS Jet 引擎 (MS Access) 时,才可以使用 OLE 提供程序读取 Excel 文件。 I noticed that you decided to use .NET interop to API but this is not a good idea: it requires installed MS Excel and doesn't recommended to use for automation on servers.我注意到您决定对 API 使用 .NET 互操作,但这不是一个好主意:它需要安装 MS Excel 并且不建议用于服务器上的自动化。

If you don't need to support old (binary) Excel formats (xls) and reading XLSX is enough I recommend to use EPPlus library.如果您不需要支持旧的(二进制)Excel 格式(xls)并且阅读 XLSX 就足够了,我建议您使用EPPlus库。 It provides simple and powerful API for both reading and writing XLSX files (and has a lot of examples):它为读取和写入 XLSX 文件提供了简单而强大的 API(并且有很多示例):

var existingFile = new FileInfo(filePath);
// Open and read the XlSX file.
using (var package = new ExcelPackage(existingFile)) {
   // access worksheets, cells etc
}

I would like to suggest the open-source & free ExcelMapper library (available on NuGet). 我想建议开源和免费的ExcelMapper库(在NuGet上可用)。

It provides a much more concise (ie readable) way of reading Excel Files compared to more conventional approaches via eg OLE queries or Microsoft.Interop.Office. 与通过例如OLE查询或Microsoft.Interop.Office的更常规方法相比,它提供了一种更加简洁(即可读)的读取Excel文件的方式。

1. Given an Excel File : 1.给定一个Excel文件

在此处输入图片说明

2.Create a Person C# object: 2创建一个Person C#对象:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

3.Read it using ExcelMapper 3,使用ExcelMapper阅读

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>();

You can also read from other worksheets, by simply passing in an additional sheet argument: 您还可以通过简单地传递一个附加的工作表参数来读取其他工作表:

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>("Sheet2");

You can install it using NuGet 您可以使用NuGet进行安装

Install-Package ExcelMapper

Disclaimer: I am not associated with ExcelMapper, but after trying various different libraries, I found this library the easiest to work with. 免责声明:我没有与ExcelMapper关联,但是在尝试了各种不同的库之后,我发现此库最容易使用。

Here is a free, short video showcasing ExcelMapper. 这是一个免费的简短视频,展示ExcelMapper。 教学视频-如何在C#中读取Excel文件 (source: excel-automation-guide.com ) (来源: excel-automation-guide.com

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

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