如何使用c#从excel文件读取数据 [英] How to read data from excel file using c#

查看:149
本文介绍了如何使用c#从excel文件读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要从excel文件读取数据。我正在使用.Net和c#进行开发。
我无法在系统中安装MS办公室。因为我的应用程序无法读取excel文件,并在加载dll for excel时发出错误。

My application needs to read data from an excel file. I am using .Net and c# for development. I cannot install MS office in the system. Because of that the my application fails to read excel file and throws an error while loading the dll for excel.

如何在没有安装ms office的系统中访问我的应用程序中的excel文件?

How can i access excel file in my application in a system where ms office is not installed?

推荐答案

可以使用 OleDB 并使用数据表中的Excel工作表(如数据库中的数据)...

There is the option to use OleDB and use the Excel sheets like datatables in a database...

只是一个例子.....

Just an example.....

string con =
  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" + 
  @"Extended Properties='Excel 8.0;HDR=Yes;'";    
using(OleDbConnection connection = new OleDbConnection(con))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); 
    using(OleDbDataReader dr = command.ExecuteReader())
    {
         while(dr.Read())
         {
             var row1Col0 = dr[0];
             Console.WriteLine(row1Col0);
         }
    }
}

此示例使用 Microsoft.Jet.OleDb.4.0 提供者打开并读取Excel文件。但是,如果文件类型为xlsx(从Excel 2007及更高版本),则需要下载 Microsoft Access数据库引擎组件,并将其安装在目标计算机上。

This example use the Microsoft.Jet.OleDb.4.0 provider to open and read the Excel file. However, if the file is of type xlsx (from Excel 2007 and later), then you need to download the Microsoft Access Database Engine components and install it on the target machine.

提供程序称为 Microsoft.ACE.OLEDB.12.0; 。注意这个组件有两个版本,一个用于32bit,另一个用于64bit。选择合适的应用程序的位置以及安装的Office版本(如果有的话)。有很多奇怪的是,该驱动程序正确地为您的应用程序工作。 看到这个问题,例如

The provider is called Microsoft.ACE.OLEDB.12.0;. Pay attention to the fact that there are two versions of this component, one for 32bit and one for 64bit. Choose the appropriate one for the bitness of your application and what Office version is installed (if any). There are a lot of quirks to have that driver correctly working for your application. See this question for example.

当然你不需要在目标机器上安装Office。

Of course you don't need Office installed on the target machine.

虽然这种方法有一些优点,我认为你应该特别注意您的问题从C#读取excel文件。在数据类型的正确解释方面存在一些问题,当单个excel单元格中存在的数据长度超过255个字符时

While this approach has some merits, I think you should pay particular attention to the link signaled by a comment in your question Reading excel files from C#. There are some problems regarding the correct interpretation of the data types and when the length of data, present in a single excel cell, is longer than 255 characters

这篇关于如何使用c#从excel文件读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆