首页 > 解决方案 > 使用c#在excel中查找每个月的最小值和最大值

问题描述

在此处输入图像描述我有一个包含全年数据的 excel。我想使用 c# 中的一些公式或代码找到每个月的低点和高点。我可以通过从日期中选择列中的值简单地将 MIN 和 MAX 公式应用于每个月的值来实现这一点1 到 31 或 30。但我不想每个月都重复同样的事情。寻找解决方案。

标签: c#excelexcel-formula

解决方案


您可以通过使用 OleDB 读取数据来做到这一点,这可能就是您正在寻找的东西......

    static void Main(string[] args)
    {
        string filepath = @"C:\temp\Data.xlsx"; //Location and name of the .xlsx? file
        string connectioninfo = $@"Provider =Microsoft.ACE.OLEDB.12.0;Data Source={ filepath };
                                   Extended Properties = 'Excel 12.0;HDR=YES;IMEX=1;';";

        string query = @"SELECT * FROM [Data$]"; //Worksheet name, if more than one year add a where clause

        List<ExcelDataModel> entries = new List<ExcelDataModel>();

        using (OleDbConnection conn = new OleDbConnection(connectioninfo))
        {
            OleDbCommand command = new OleDbCommand(query, conn);

            conn.Open();

            OleDbDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
                while (reader.Read())
                    entries.Add(new ExcelDataModel { DT = Convert.ToDateTime(reader[0]),
                                                High = double.Parse(reader[1].ToString()),
                                                Low = double.Parse(reader[2].ToString()) });

            conn.Close();
        }

        var values = entries.GroupBy(x => x.DT.Month).Select(i => new { dt = i.Key, High = i.Max(y => y.High), Low = i.Min(y => y.Low) }).ToList();

        //Do whatever you need with the records
        values.ForEach(month => { Console.WriteLine($"Month: { month.dt } \t Highest: { month.High } \t Lowest: { month.Low }"); });

        Console.ReadLine();
    }

我还添加了一个类来临时存储 Excel 工作表中的所有行:

public class ExcelDataModel
{
    public DateTime DT { get; set; }
    public double High { get; set; }
    public double Low { get; set; }
}

推荐阅读