从 C# 读取 Excel 文件 [英] Reading Excel files from C#
问题描述
是否有免费或开源库可以直接从 C# 程序读取 Excel 文件 (.xls)?
Is there a free or open source library to read Excel files (.xls) directly from a C# program?
不需要太花哨,只需选择一个工作表,将数据读取为字符串即可.到目前为止,我一直在使用 Excel 的导出到 Unicode 文本功能,并解析生成的(制表符分隔的)文件,但我想消除手动步骤.
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"];
这是我常用的.这有点不同,因为我通常在编辑表格时使用 AsEnumerable():
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();
因为这让我可以使用 LINQ 从字段中搜索和构建结构.
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屋!