问题描述
有一个免费或开源库直接从C#程序读取Excel文件(.xls的)?
它并不需要太花哨,只是为了选择一个工作表,并作为字符串读取数据。到目前为止,我一直在使用导出到Excel的统一code文本功能,并解析结果(制表符分隔)文件,但我想要消除手动步骤。
变种文件名=的String.Format({0} \\\\ fileNameHere,Directory.GetCurrentDirectory());
VAR的connectionString =的String.Format(供应商= Microsoft.Jet.OLEDB.4.0;数据源= {0};扩展属性= Excel的8.0;文件名);VAR适配器=新OleDbDataAdapter的(SELECT * FROM [workSheetNameHere $]的connectionString);
变种DS =新的DataSet();adapter.Fill(DSanyNameHere);数据表数据= ds.Tables [anyNameHere];
这是我平时使用。这是一个有点不同,因为我通常在表格的编辑粘AsEnumerable():
VAR数据= ds.Tables [anyNameHere] AsEnumerable()。
,因为这让我使用LINQ搜索和领域建立结构。
VAR的查询= data.Where(X => x.Field<串GT(phoneNumber的)=的String.Empty!)。选择(X =>
新MyContact
{
的firstName = x.Field<串GT;(名),
的lastName = x.Field<串GT(姓),
phoneNumber的= x.Field<串GT(电话号码),
});
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文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!