【发布时间】:2020-05-19 18:10:42
【问题描述】:
我写了一个 C# 程序,试图用这样的公式创建一个 Excel 工作表
using Excel = Microsoft.Office.Interop.Excel;
// the details of the class
Excel.Workbook obook;
Excel.Application oexcel = new Excel.Application();
oexcel.Application.DisplayAlerts = false;
obook = oexcel.Application.Workbooks.Add(Type.Missing);
Excel.Worksheet osheet;
osheet = (Excel.Worksheet)obook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// create arrray to store formula
string[,] excelarray3 = new string[sample1.Width * sample1.Height, 1];
int rowct=0;
// some logic here to define the value of rowct (i.e. row count in excel)
// using for loop to assign formula into the array i.e.
for (int i =0; i <= rowct; i++){
excelarry3[i,0]= "AND( A" + (i+1).ToString() + ">=AA1,A"+ (i+1).ToString() + "<=AB1,B"+ (i+1).ToString() + ">=AB1)";
}
// then assign value to excel
Excel.Range range3 = osheet.Range[osheet.Cells[2, 14], osheet.Cells[rowct + 1, 14]];
range3.Formula = excelarray3;
当我打开生成的表格时,分配给 N 列中单元格的那些公式显示为文本,而不是公式的计算结果,如下图所示
我根本没有定义单元格格式。并且我将公式放入N、Q和T列。不同之处在于Q、T列中的公式是一一分配给单元格的,而分配给N列的公式是将字符串数组粘贴到Excel范围内。
我很确定公式是有效的,因为在我选择单元格然后按 Enter 键后公式开始计算
【问题讨论】:
-
正在使用互操作?
-
您好 Ka001,您能告诉我们您使用的是哪个库吗?另外,range1 是什么类型?作为一种猜测,我建议您需要设置公式,而不是单元格的值,但向我们提供上述信息会有所帮助。
-
是的,我正在使用互操作。我还编辑了帖子以显示我的代码的详细信息以供您参考。我尝试使用公式,但问题似乎仍然存在
-
如果我将Excel公式一个一个地分配给单元格,似乎可以工作,但如果使用数组分配到一个范围内,则不能工作。但由于数据量很大(每张 30 个工作表 x 7000 行),我无法一一分配,这使得程序运行非常缓慢