从C#读取Excel文件 [英] Reading Excel files from C#

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

问题描述

有没有一个免费的或开源的库可以直接从C#程序读取Excel文件(.xls)?



它不需要太花哨,只是选择工作表并将数据读为字符串。到目前为止,我一直在使用Excel的导出到Unicode文本功能,并解析生成的(制表符分隔)文件,但是我想消除手动步骤。

解决方案

  var fileName = string.Format({0} \\fileNameHere,Directory.GetCurrentDirectory()); 
var connectionString = string.Format(Provider = Microsoft.Jet.OLEDB.4.0; data source = {0};扩展属性= Excel 8.0;,fileName);

var adapter = new OleDbDataAdapter(SELECT * FROM [workSheetNameHere $],connectionString);
var ds = new DataSet();

adapter.Fill(ds,anyNameHere);

DataTable data = ds.Tables [anyNameHere];

这是我通常使用的。这有点不一样,因为我通常在表的编辑中粘贴一个AsEnumerable():

  var data = ds.Tables [ anyNameHere] AsEnumerable(); 

这样,我可以使用LINQ从字段中搜索和构建结构。

  var query = data.Where(x => x.Field< string>(phoneNumber)!= string.Empty).Select(x => 
new MyContact
{
firstName = x.Field< string>(First Name),
lastName = x.Field< string>(Last Name ),
phoneNumber = x.Field< string>(电话号码),
});


Is there a free or open source library to read Excel files (.xls) directly from a C# program?

It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.

解决方案

var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
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, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];

This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables:

var data = ds.Tables["anyNameHere"].AsEnumerable();

as this lets me use LINQ to search and build structs from the fields.

var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
                new MyContact
                    {
                        firstName= x.Field<string>("First Name"),
                        lastName = x.Field<string>("Last Name"),
                        phoneNumber =x.Field<string>("Phone Number"),
                    });

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

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