c# - 使用c#在excel中查找每个月的最小值和最大值
问题描述
我有一个包含全年数据的 excel。我想使用 c# 中的一些公式或代码找到每个月的低点和高点。我可以通过从日期中选择列中的值简单地将 MIN 和 MAX 公式应用于每个月的值来实现这一点1 到 31 或 30。但我不想每个月都重复同样的事情。寻找解决方案。
解决方案
您可以通过使用 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; }
}
推荐阅读
- python - 使用 groupby (Pandas) 计算一列的唯一值
- vue.js - 如何从中间件或插件设置 nuxtjs 标题和元?
- tensorflow-serving - TensorFlow Serving 是否允许插件(动态链接的用户扩展)?
- junit - 如何使用 Junit LauncherDiscoveryRequest 从 Java 项目的另一个模块中的包中发现测试?
- javascript - 参考错误,但日期已定义。请指出我做错了什么
- javascript - window.location.reload 不断刷新页面
- python - 如何获取 pip 安装 `data_files` 的路径?
- java - MarkLogic Java API 中 cts:element-query 的等价物
- python - 从文本中提取 x 和 y 数据
- java - Java LocalDate 在保存到 MySQL 数据库时存储为半随机天数