Back to Devexpress

Use the Excel Export API to Create Shared Formulas

officefileapi-116625-excel-export-library-formulas-how-to-create-shared-formulas.md

latest2.4 KB
Original Source

Use the Excel Export API to Create Shared Formulas

  • Sep 19, 2023
  • 2 minutes to read

A shared formula consists of a formula in one cell marked as shared and the cells referenced by the shared formula. The referenced cells obtain their own version of the formula, so if cell D2 has the formula B2*C2, then cell D3 would have the formula B3*C3 etc.

It takes two steps to build a shared formula. First, add a formula to the first cell in a range - it is the host formula. Next, add a reference to the host formula to any other cell of the range. The IXlCell.SetSharedFormula method with different parameters serves both steps, as illustrated in the code below.

View Example

csharp
// Create data rows.
for (int i = 0; i < 4; i++) {
    using (IXlRow row = sheet.CreateRow()) {
        using (IXlCell cell = row.CreateCell()) {
            cell.Value = product[i];
        }
        using (IXlCell cell = row.CreateCell()) {
            cell.Value = qty[i];
        }
        using (IXlCell cell = row.CreateCell()) {
            cell.Value = price[i];
        }
        using (IXlCell cell = row.CreateCell()) {
            // Use the shared formula to calculate the amount per product. 
            if (i == 0)
                cell.SetSharedFormula("B2*C2", XlCellRange.FromLTRB(3, 1, 3, 4));
            else
                cell.SetSharedFormula(new XlCellPosition(3, 1));
        }
    }
}
vb
' Create data rows.
For i As Integer = 0 To 3
    Using row As IXlRow = sheet.CreateRow()
        Using cell As IXlCell = row.CreateCell()
            cell.Value = product(i)
        End Using
        Using cell As IXlCell = row.CreateCell()
            cell.Value = qty(i)
        End Using
        Using cell As IXlCell = row.CreateCell()
            cell.Value = price(i)
        End Using
        Using cell As IXlCell = row.CreateCell()
            ' Use the shared formula to calculate the amount per product. 
            If i = 0 Then
                cell.SetSharedFormula("B2*C2", XlCellRange.FromLTRB(3, 1, 3, 4))
            Else
                cell.SetSharedFormula(New XlCellPosition(3, 1))
            End If
        End Using
    End Using
Next i