是否有免费或开源的库可以直接从c#程序中读取Excel文件(.xls) ?
它不需要太花哨,只需选择一个工作表并将数据作为字符串读取即可。到目前为止,我一直在使用Excel的Export to Unicode文本功能,并解析生成的(以制表符分隔的)文件,但我想消除手动步骤。
是否有免费或开源的库可以直接从c#程序中读取Excel文件(.xls) ?
它不需要太花哨,只需选择一个工作表并将数据作为字符串读取即可。到目前为止,我一直在使用Excel的Export to Unicode文本功能,并解析生成的(以制表符分隔的)文件,但我想消除手动步骤。
当前回答
我们使用的解决方案需要:
允许读取/写入Excel生成的文件 性能要快(不像使用com那样) 独立于MS Office(需要在客户端没有安装MS Office的情况下也能使用) 免费或开源(但要积极开发)
有几种选择,但我们发现NPoi(。NET端口的Java长期存在的Poi开源项目)是最好的: http://npoi.codeplex.com/
它还允许使用.doc和.ppt文件格式
其他回答
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():
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>("Phone Number"),
});
我推荐FileHelpers库,这是一个免费的,易于使用的。net库,用于从EXCEL中导入/导出数据,文件,字符串或流中的固定长度或分隔记录+更多。
Excel数据链接文档部分 http://filehelpers.sourceforge.net/example_exceldatalink.html
这是我在Excel 2003中使用的:
Dictionary<string, string> props = new Dictionary<string, string>();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
}
string properties = sb.ToString();
using (OleDbConnection conn = new OleDbConnection(properties))
{
conn.Open();
DataSet ds = new DataSet();
string columns = String.Join(",", columnNames.ToArray());
using (OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT " + columns + " FROM [" + worksheet + "$]", conn))
{
DataTable dt = new DataTable(tableName);
da.Fill(dt);
ds.Tables.Add(dt);
}
}
如果只是包含在Excel文件中的简单数据,则可以通过ADO.NET读取数据。请看下面列出的连接字符串:
http://www.connectionstrings.com/?carrier=excel2007 或 http://www.connectionstrings.com/?carrier=excel
对
更新:然后你可以读取工作表通过选择*从[Sheet1$]
您可以编写一个excel电子表格,加载给定的excel电子表格并将其保存为CSV(而不是手动操作)。
然后你可以用c#自动化它。
一旦它在csv中,c#程序就可以理解它。
(此外,如果有人让你用excel编程,最好假装你不知道怎么做)
(编辑:啊,是的,rob和Ryan都是对的)