Insert Formula in Cell using C# (OpenXML and EPPlus Library)


Sharing the sample code, we can use to insert forumala in a particular cell in Excel Spreadsheet.

First using Open XML SDK

</p>
<p>public static void UpdateExcelUsingOpenXMLSDK(string fileName)<br />
{<br />
// Open the document for editing.<br />
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(fileName, true))<br />
{<br />
// Access the main Workbook part, which contains all references.<br />
WorkbookPart workbookPart = spreadSheet.WorkbookPart;<br />
// get sheet by name<br />
Sheet sheet = workbookPart.Workbook.Descendants&lt;Sheet&gt;().Where(s =&gt; s.Name == "Sheet1").FirstOrDefault();</p>
<p>// get worksheetpart by sheet id<br />
WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id.Value) as WorksheetPart;</p>
<p>// The SheetData object will contain all the data.<br />
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild();</p>
<p>Cell formulaCell = InsertCellInWorksheet("B", 10, worksheetPart);<br />
formulaCell.DataType = new EnumValue&lt;CellValues&gt;(CellValues.Number);<br />
formulaCell.CellFormula = new CellFormula("SUM(B2:B7)");</p>
<p>// Save the worksheet.<br />
worksheetPart.Worksheet.Save();</p>
<p>// for recacluation of formula<br />
spreadSheet.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;<br />
spreadSheet.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;</p>
<p>}<br />
}</p>
<p>private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)<br />
{<br />
Worksheet worksheet = worksheetPart.Worksheet;<br />
SheetData sheetData = worksheet.GetFirstChild&lt;SheetData&gt;();<br />
string cellReference = columnName + rowIndex;</p>
<p>// If the worksheet does not contain a row with the specified row index, insert one.<br />
Row row;<br />
if (sheetData.Elements&lt;Row&gt;().Where(r =&gt; r.RowIndex == rowIndex).Count() != 0)<br />
{<br />
row = sheetData.Elements&lt;Row&gt;().Where(r =&gt; r.RowIndex == rowIndex).First();<br />
}<br />
else<br />
{<br />
row = new Row() { RowIndex = rowIndex };<br />
sheetData.Append(row);<br />
}</p>
<p>// If there is not a cell with the specified column name, insert one.<br />
if (row.Elements&lt;Cell&gt;().Where(c =&gt; c.CellReference.Value == columnName + rowIndex).Count() &gt; 0)<br />
{<br />
return row.Elements&lt;Cell&gt;().Where(c =&gt; c.CellReference.Value == cellReference).First();<br />
}<br />
else<br />
{<br />
// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.<br />
Cell refCell = null;<br />
foreach (Cell cell in row.Elements&lt;Cell&gt;())<br />
{<br />
if (cell.CellReference.Value.Length == cellReference.Length)<br />
{<br />
if (string.Compare(cell.CellReference.Value, cellReference, true) &gt; 0)<br />
{<br />
refCell = cell;<br />
break;<br />
}<br />
}<br />
}</p>
<p>Cell newCell = new Cell() { CellReference = cellReference };<br />
row.InsertBefore(newCell, refCell);</p>
<p>worksheet.Save();<br />
return newCell;<br />
}<br />
}</p>
<p>

Using EPPlus

https://www.nuget.org/packages/EPPlus/

</p>
<p>public void UpdateExcelUsingEPPlus(string fileName)<br />
{<br />
FileInfo fileInfo = new FileInfo(fileName);<br />
ExcelPackage p = new ExcelPackage(fileInfo);<br />
ExcelWorksheet myWorksheet = p.Workbook.Worksheets["Sheet1"];</p>
<p>myWorksheet.Cells["B15"].Formula = "SUM(B2:B7)";</p>
<p>p.Save();</p>
<p>}</p>
<p>

Hope it helps..

Advertisements
Advertisement

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

2 thoughts on “Insert Formula in Cell using C# (OpenXML and EPPlus Library)”

Please share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog & Website of Paul Andrew

Technical Leadership Centred Around the Microsoft Data Platform

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Dynamics 365 Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM

EVOLVED365

Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

%d bloggers like this: