You can use the OpenXML SDK to read Xlsx files.
To do this you need to add a reference to the OpenXML library which can be done via the nuget package (you'll also need a reference to WindowsBase). You then need to load the spreadsheet, find the sheet you're interested in and iterate the cells.
Each Cell
has a CellFormula
property which will be non-null if there is a formula in that cell.
As an example, the following code will iterate each cell and output a line for any cell that has a formula. it will return true
if any cell has a formula in it; otherwise it will return false
:
public static bool OutputFormulae(string filename, string sheetName)
{
bool hasFormula = false;
//open the document
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
{
//get the workbookpart
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
//get the correct sheet
Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).First();
if (sheet != null)
{
//get the corresponding worksheetpart
WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;
//iterate the child Cells
foreach (Cell cell in worksheetPart.Worksheet.Descendants<Cell>())
{
//check for a formula
if (cell.CellFormula != null && !string.IsNullOrEmpty(cell.CellFormula.Text))
{
hasFormula = true;
Console.WriteLine("Cell {0} has the formula {1}", cell.CellReference, cell.CellFormula.Text);
}
}
}
}
return hasFormula;
}
This can be called with the name of the file and the name of the sheet you're interested in although it would be trivial to update the code to iterate all sheets. An example call:
bool formulaExistsInSheet = OutputFormulae(@"d:\test.xlsx", "Sheet1");
Console.WriteLine("Formula exists? {0}", formulaExistsInSheet);
An example output from the above:
Cell C1 has the formula A1+B1
Cell B3 has the formula C1*20
Formula exists? True
If you're only interested if there are any cells in the sheet that have a formula you can simplify the above by using the Any
extension method:
public static bool HasFormula(string filename, string sheetName)
{
bool hasFormula = false;
//open the document
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
{
//get the workbookpart
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
//get the correct sheet
Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).First();
if (sheet != null)
{
//get the corresponding worksheetpart
WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;
hasFormula = worksheetPart.Worksheet.Descendants<Cell>().Any(c =>
c.CellFormula != null && !string.IsNullOrEmpty(c.CellFormula.Text));
}
}
return hasFormula;
}