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

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


当前回答

这是我在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);
    }
}

其他回答

ExcelMapper是一个开源工具(http://code.google.com/p/excelmapper/),可用于将Excel工作表作为强类型对象读取。它同时支持xls和xlsx格式。

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

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

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"),
                    });

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