如何使用Gembox将Excel函数转换为C#中的实际值

时间:2018-08-13 13:59:42

标签: c# excel gembox-spreadsheet

我们有一个自动供稿,由我们的ERP系统使用C#和GemBox填充,该供稿生成带有价格的Excel文件。

我们有一个公式来汇总价格,但是我们发现其他Web系统看不到实际值,因为函数为0,只能在打开Excel文件时计算得出。我知道您可以复制并粘贴为值以获取函数的实际值,但这需要在代码中进行。为此,我们是否需要在后端使用临时表?

如何将代码中的Excel函数转换为实际值?

https://www.gemboxsoftware.com/spreadsheet/examples/excel-cell-formula/206

1 个答案:

答案 0 :(得分:1)

如果该文件曾经被打开过,则该单元格绝对应该具有基于其最后一次计算的值,您可以从ADO中读取该值。如果从未打开过该文件(即,通过将函数插入到单元格以编程方式创建的文件),则可能是问题的根本原因。

我对GemBox并不熟悉,但是从文档中可以看出这是受支持的。

GemBox.Spreadsheet支持单个Excel单元格计算,工作表计算和整个文件计算:

https://www.gemboxsoftware.com/spreadsheet/examples/excel-formula-calculation/901

using System;
using GemBox.Spreadsheet;

class Sample
{
    [STAThread]
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        ExcelFile ef = new ExcelFile();
        ExcelWorksheet ws = ef.Worksheets.Add("Formula Calculation");

        // Some formatting.
        ExcelRow row = ws.Rows[0];
        row.Style.Font.Weight = ExcelFont.BoldWeight;

        ExcelColumn col = ws.Columns[0];
        col.SetWidth(250, LengthUnit.Pixel);
        col.Style.HorizontalAlignment = HorizontalAlignmentStyle.Left;
        col = ws.Columns[1];
        col.SetWidth(250, LengthUnit.Pixel);
        col.Style.HorizontalAlignment = HorizontalAlignmentStyle.Right;

        // Use first row for column headers.
        ws.Cells["A1"].Value = "Formula";
        ws.Cells["B1"].Value = "Calculated value";

        // Enter some Excel formulas as text in first column.
        ws.Cells["A2"].Value = "=1 + 1";
        ws.Cells["A3"].Value = "=3 * (2 - 8)";
        ws.Cells["A4"].Value = "=3 + ABS(B3)";
        ws.Cells["A5"].Value = "=B4 > 15";
        ws.Cells["A6"].Value = "=IF(B5, \"Hello world\", \"World hello\")";
        ws.Cells["A7"].Value = "=B6 & \" example\"";
        ws.Cells["A8"].Value = "=CODE(RIGHT(B7))";
        ws.Cells["A9"].Value = "=POWER(B8, 3) * 0.45%";
        ws.Cells["A10"].Value = "=SIGN(B9)";
        ws.Cells["A11"].Value = "=SUM(B2:B10)";

        // Set text from first column as second row cell's formula.
        int rowIndex = 1;
        while (ws.Cells[rowIndex, 0].ValueType != CellValueType.Null)
            ws.Cells[rowIndex, 1].Formula = ws.Cells[rowIndex++, 0].StringValue;

        // GemBox.Spreadsheet supports single Excel cell calculation, ...
        ws.Cells["B2"].Calculate();

        // ... Excel worksheet calculation,
        ws.Calculate();

        // ... and whole Excel file calculation.
        ws.Parent.Calculate();

        ef.Save("Formula Calculation.xlsx");
    }
}