在C#中读取Excel中的公式并生成其计算结果可以使用开源库如EPPlus或Microsoft.Office.Interop.Excel,如果是.xlsm宏文件需用到Microsoft.Office.Interop.Excel。
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("Calculated Result (A2): " + result);
? ? ? ? }
? ? }
}
?
using System;
using Microsoft.Office.Interop.Excel;
class Program
{
? ? static void Main()
? ? {
? ? ? ? string filePath = "your_excel_file.xlsm";
? ? ? ? // 创建一个 Excel 应用程序对象
? ? ? ? Application excelApp = new Application();
? ? ? ? // 打开工作簿
? ? ? ? Workbook workbook = excelApp.Workbooks.Open(filePath);
? ? ? ? // 获取第一个工作表
? ? ? ? Worksheet worksheet = workbook.Sheets[1];
? ? ? ? // 设置 A1 的值
? ? ? ? Range rangeA1 = worksheet.Cells["A1"];
? ? ? ? rangeA1.Value = 5;
? ? ? ? // 计算整个工作表中的公式
? ? ? ? workbook.Calculate();
? ? ? ? // 获取 A2 的值
? ? ? ? Range rangeA2 = worksheet.Cells["A2"];
? ? ? ? double result = (double)rangeA2.Value;
? ? ? ? Console.WriteLine("Input Value (A1): " + rangeA1.Value);
? ? ? ? Console.WriteLine("Calculated Result (A2): " + result);
? ? ? ? // 关闭工作簿和 Excel 应用程序
? ? ? ? workbook.Close(false);
? ? ? ? excelApp.Quit();
? ? }
}
?