简体   繁体   English

C#读取Excel文件

[英]Reading Excel Files in C#

如何打开和读取 excel 文件中的所有数据以执行一些操作,例如将它们写入数据库...

You can use the default library that comes with the .NET framework in order to use the Excel.Application Object and therefore the Workbook and Worksheets objects, so you can access Excel files, read or manipulate them您可以使用 .NET 框架附带的默认库来使用 Excel.Application 对象,从而使用 Workbook 和 Worksheets 对象,以便您可以访问 Excel 文件、读取或操作它们

You can add it to your project by using the Add Reference option, the library is called您可以使用 Add Reference 选项将其添加到您的项目中,该库称为

Microsoft.Office.Interop.Excel微软.Office.Interop.Excel

Hope this helps希望这可以帮助

Assuming that the Excel files are in a table format, I'd suggest that the best way would be using OleDB.假设 Excel 文件是表格格式,我建议最好的方法是使用 OleDB。 This page has a very basic sample that should show you how to get started.这个页面有一个非常基本的示例,它应该向您展示如何开始。

If you're unable to use OleDB for some reason, then you could use Excel Automation.如果由于某种原因无法使用 OleDB,则可以使用 Excel 自动化。 This is not recommended if it's on a server though and will in general be slower and less stable than OleDB, but you will be able to do pretty much anything you need.如果它在服务器上,则不建议这样做,并且通常比 OleDB 慢且不稳定,但是您几乎可以做任何您需要的事情。

您可以使用 com 自动化http://support.microsoft.com/kb/302096自动化 Excel,但如果您在网络服务器上,则需要使用第三方库,如http://sourceforge.net/projects/koogra /

There are several ways:有几种方式:

  • If *.xslx (the new XML based format) is used, you can open that file and read the XML File如果使用 *.xslx(新的基于 XML 的格式),您可以打开该文件并读取 XML 文件
  • You can read it with Excel COM Interop (not recomended on a Server!)您可以使用 Excel COM Interop 阅读它(不推荐在服务器上使用!)
  • You can use a ODBC Data Source您可以使用 ODBC 数据源

Starting with Office 2007, you can use OpenXML to query/manipulate office documents.从 Office 2007 开始,您可以使用 OpenXML 来查询/操作办公文档。 The .xlsx files (all Office .???x files) are zipped up XML files. .xlsx 文件(所有 Office .???x 文件)是压缩的 XML 文件。

ExcelToEnumerable is a great solution if you want to map Excel data to a list of classes, eg:如果您想将 Excel 数据映射到类列表, ExcelToEnumerable是一个很好的解决方案,例如:

var filePath = "/Path/To/ExcelFile.xlsx";
IEnumerable<MyClass> myClasses = filePath.ExcelToEnumerable<MyClass>();

Disclaimer .免责声明 I am the author of ExcelToEnumerable.我是 ExcelToEnumerable 的作者。

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

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