从列

时间:2015-11-12 13:05:56

标签: c# excel excel-interop

必须使用Excel.interop获取每列不同的数据并存储到Dictionary(或数组)。我尝试了以下代码,但它与Excel.interop不一致。

      var excel = new ExcelQueryFactory("worksheetFileName");
      var distinctNames = (from row in excel.WorkSheet() select row["ColB"]).Distinct();

请提供Excel.Interop代码段/代码,逐列获取不同的值并存储在数组中。

1 个答案:

答案 0 :(得分:1)

对于此操作,使用Excel自动化是没有意义的,而谨慎的做法是使用OleDb,除非有合理的理由使用Excel自动化。

示例,图1是一个创建连接字符串的函数,可以在任何项目中使用,而图2是用于读取数据。

为了使用Excel自动化,我们可以打开自己的物体,如果发生崩溃或者你没有正确编码(或者我称之为双点规则),当物体因为无法释放而被丢弃时如何创建和使用OleDb不会发生的自动化对象。现在,如果你想要格式化而不是我们转向自动化。

frank = function(x)
{
    x[, res := NA_character_]
    for(v in rev(names(x))[-1]) x[is.na(res), res := get(v)]
    return(x$res)       
}

DAT1 = as.data.table(lapply(ceiling(seq(0, 1e4, length.out = 1e2)), 
                     function(n) c(rep(NA, n), sample(letters, 3e5 - n, TRUE))))
DAT2 = copy(DAT1)
microbenchmark::microbenchmark(alex(as.list(DAT1)), 
                               { frank(DAT2); DAT2[, res := NULL] }, 
                               times = 30)
#Unit: milliseconds
#                                            expr       min        lq    median        uq       max neval
#                             alex(as.list(DAT1))  102.9767  108.5134  117.6595  133.1849  166.9594    30
# {     frank(DAT2)     DAT2[, `:=`(res, NULL)] } 1413.3296 1455.1553 1497.3517 1540.8705 1685.0589    30
identical(alex(as.list(DAT1)), frank(DAT2))
#[1] TRUE

用于读取Sheet2中第一列的代码并获取不同的值,在这种情况下,我正在使用日期为字符串的列来处理列表,其中文件与应用程序可执行文件位于同一文件夹中

public string ConnectionString(string FileName, string Header)
{
    OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
    if (System.IO.Path.GetExtension(FileName).ToUpper() == ".XLS")
    {
        Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
        Builder.Add("Extended Properties", string.Format("Excel 8.0;IMEX=1;HDR={0};", Header));
    }
    else
    {
        Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
        Builder.Add("Extended Properties", string.Format("Excel 12.0;IMEX=1;HDR={0};", Header));
    }

    Builder.DataSource = FileName;

    return Builder.ConnectionString;
}