C# Excel Add In: Get active worksheet as XML

288 views Asked by At

I have a working Word add in, which saves the selected part of the document (including images, tables, etc) as an XML string in a database. The add in can also retrieve previously saved XML strings and insert it into the current position of the currently open document, preserving styling and formatting.

I want to do almost the same for Excel. I want to get an XML string that represents the active worksheet, save that to the database and then later retrieve that XML string and insert it as a worksheet into the active workbook.

The problem is, I can't figure out how to obtain that XML string, nor can I figure out how to insert it as a worksheet. I have been experimenting and searching for hours, but to no avail.

Getting the active sheet seems easy:

dynamic sheet = Globals.ThisAddIn.Application.ActiveSheet;

But I haven't been able to get any further.

For reference, this is how I got the XML string in Word:

Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
string xmlString = currentSelection.XML;

To insert it, I used:

string xmlString = ...; // Read the string for the database.
Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
currentSelection.InsertXML(xmlString);
1

There are 1 answers

1
Alex H On

Take a look in this sample. In this sample they are converting the Excel Sheet into a DataTable by iterating over the rows and cells and converting the DataTable into a string.