是否有免费或开源的库可以直接从c#程序中读取Excel文件(.xls) ?

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


当前回答

SpreadsheetGear for . net是一个Excel兼容的电子表格组件。您可以在我们产品页面的右侧看到我们的客户对性能的评价。您可以自己尝试使用免费的、功能齐全的评估。

其他回答

Excel软件包是一个开源的(GPL)组件,用于读取/写入Excel 2007文件。我在一个小项目中使用了它,它的API很简单。只能使用XLSX (Excel 200&),不能使用XLS。

源代码似乎组织良好,易于处理(如果您像我一样需要扩展功能或修复小问题)。

起初,我尝试了ADO。Net (Excel连接字符串)方法,但它充满了讨厌的黑客——例如,如果第二行包含一个数字,它将为下面的列中的所有字段返回整数,并悄悄删除任何不匹配的数据。

这是我在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更加简洁。

http://excelwrapperdotnet.codeplex.com/

如果我离题了请原谅,但这不是Office PIA的用途吗?

不是免费的,但是在最新的Office中有一个非常好的自动化。net API。(有一个API已经有很长一段时间了,但是讨厌的COM)你可以在代码中做任何你想要/需要的事情,而Office应用程序仍然是隐藏的后台进程。