逐列获取不同的值

本文关键字:获取 | 更新日期: 2023-09-27 18:21:42

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

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

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

逐列获取不同的值

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

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

为了使用Excel自动化,如果发生崩溃或您没有正确编码(我称之为两点规则),当由于您创建和使用自动化对象的方式而无法释放对象时,我们会向未处理的对象敞开大门,而OleDb不会发生这种情况。现在,如果您想要格式化,我们将转向自动化。

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;
}

读取Sheet2中第一列并获得不同值的代码,在这种情况下,我将日期作为字符串的列放入List中,其中文件与应用程序可执行位于同一文件夹中

private List<string> DemoDistinct()
{
    List<string> dateList = new List<string>();
    DataTable dt = new DataTable();
    using (OleDbConnection cn = new OleDbConnection { ConnectionString = ConnectionString(System.IO.Path.Combine(Application.StartupPath, "WS1.xlsx"), "Yes") })
    {
        cn.Open();
        using (OleDbCommand cmd = new OleDbCommand
        {
            CommandText = "SELECT DISTINCT [Dates] FROM [Sheet2$]",
            Connection = cn
        }
         )
        {
            OleDbDataReader dr = cmd.ExecuteReader();
            dt.Load(dr);
            dateList = dt
                .AsEnumerable()
                .Select(row => row.Field<DateTime>("Dates").ToShortDateString()).ToList();                      
        }
    }
    return dateList;
}