One of my recent projects required me to extensively manipulate Excel sheets (read/write data)
I felt OpenXML was the way to go since that’s the new file format which Microsoft is using these days (Office 2007/2010).
Even when using OpenXML, you need to know the nitty-gritty and low level understanding of the Excel document breakdown which discourages many developers from taking the plunge into OpenXML development.
While searching for a solution better than OpenXML, i stumbled upon ExtremeML.
Its a nifty utility that creates a wrapper layer on top of OpenXML, allowing the developers to easily work with OpenXML without much concern about the internal working.
ExtremeML adds new power to the OpenXML SDK 2.0, enabling packages to be created and edited via an intuitive object model and freeing developers from the burden of implementing the low-level detail of OpenXML.
Below is a piece of code that shows how to open an excel file, read values, manipulate values and save the changes back to the Excel document.
/// <summary>
/// Manupulates an excel sheet
/// </summary>
/// <param name="filePath">The path to the excel sheet.</param>
public void ManipulateExcel(string filePath)
{
//Open document
using (var document = SpreadsheetDocumentWrapper.Open(filePath))
{
//Get the worksheet
var worksheet = document.WorkbookPart.WorksheetParts["MyWorksheet"];
//Iterate all rows in the spreadsheet
foreach(var row in worksheet.Worksheet.SheetData.Rows)
{
//Iterate all cells in a row
foreach (var cell in row.Cells)
{
// Get value for the Cell as strongly typed
var cellValue = cell.GetValue<string>();
/*
* manipulate the cell value as required
*/
// Set value for the Cell
cell.SetValue(cellValue);
}
}
// The file is auto saved when the document is disposed
}
}