在C#中读取Excel中的公式并生成其计算结果可以使用开源库如EPPlus或Microsoft.Office.Interop.Excel,如果是.xlsm宏文件需用到Microsoft.Office.Interop.Excel。
1.EPPlus方式
using System;
using OfficeOpenXml;
class Program
{
static void Main()
{
string filePath = "your_excel_file.xlsx";
using (var package = new ExcelPackage(new System.IO.FileInfo(filePath)))
{
var worksheet = package.Workbook.Worksheets[0]; // 选择第一个工作表
// 设置 A1 的值
worksheet.Cells["A1"].Value = 5;
// 计算整个工作表中的公式
worksheet.Calculate();
// 获取 A2 的值
double result = worksheet.Cells["A2"].GetValue<double>();
Console.WriteLine("Input Value (A1): " + worksheet.Cells["A1"].Value);
Console.WriteLine("Ca