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

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

问题描述

我的应用程序需要从一个excel文件中读取数据。我使用.NET和C#进行开发。 我无法安装微软办公系统。正因为如此,在我的应用程序无法读取Excel文件并抛出一个错误,同时加载DLL为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.

我怎样才能访问Excel文件在我的应用程序在不安装微软的Office系统?

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数据访问组件和目标计算机上安装它。

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 Data Access components and install it on the target machine.

该供应商被称为 Microsoft.ACE.OLEDB.12.0; 。 (要注意的是,有两个版本的组件,一个是32位,一个是64位的,选择一个合适的应用程序和操作系统的目标计算机上的位数)

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 OS on target machine)

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

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

虽然这种方法有一定的可取之处,我想你应该特别注意你的问题的从C#阅读Excel文件。有关于数据类型的正确跨pretation而当数据present在一个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天全站免登陆