Archive for category LINQ

Using ExtremeML with OpenXML SDK

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
	}
}

Post to Twitter

Modify CDATA Element in XML File using LINQ to XML

Yesterday I came across the following situation:

1) Load a XML File.

2) Parse the elements that match certain criteria.

3) Set the elements value to a new data

The only problem in the above situation was that I was dealing with CDATA inside the element.

Sample XML:

<employees>
    <employee>
        <description>
            <![CDATA[Lorem Ipsum]]>
        </description>
    </employee>
    ....
</employees>

The C# fragment that will allow you to manipulate the above elment is:

public void ParseEmployeeDescription(XDocument document)
{
	var result = from e in document.Descendants("description")
				 select e;
	foreach (var element in result)
	{
		if(/*Some condition matches*/)
		{
			var temp = element.Value;

			temp += "modified";
			//Replace with new data in the CDATA tag
			((XCData)element.FirstNode).Value = pTagData;

		}

	}
	document.Save("new_employees.xml");
}

Hopefully this helps someone :)

Post to Twitter

Tags: , , ,