These are the steps to create a spreadsheet document using OpenXML SDK
1. Add a reference to Microsoft.Office.DocumentFormat.OpenXml (from .Net tab, provided you have installed SDK)
2. use the namespace
using Microsoft.Office.DocumentFormat.OpenXml.Packaging;
3. Create workbook document and add workbook and worksheet
SpreadsheetDocument spDoc = SpreadsheetDocument.Create(@"c:\testnow.xlsx", SpreadsheetDocumentType.Workbook);
WorkbookPart wbPart = spDoc.AddWorkbookPart();
WorksheetPart wsPart = wbPart.AddNewPart<WorksheetPart>();
4. generate the id for sheet
string relId = wbPart.GetIdOfPart(wsPart);
5. Either create workbook.xml and sheet1.xml file (any file name) or load the existing file. Here, I am loading the existing file
XmlDocument xwb = new XmlDocument();
xwb.Load(@"..\..\workbook.xml");
6. Locate the sheet element and set the r;id attribute to the one we generated in the step 4
XmlNamespaceManager nsManager = new XmlNamespaceManager(xwb.NameTable);
nsManager.AddNamespace("default", xwb.DocumentElement.NamespaceURI);
XmlNodeList nodelist = xwb.SelectNodes("//default:sheets/default:sheet", nsManager);
foreach (XmlNode node in nodelist)
{
string sheetName = node.Attributes["name"].Value;
if (sheetName == "Sheet1")
{
node.Attributes["r:id"].Value = relId;
}
}
7. Load the modified xml file into the workbook part
Stream stream = wbPart.GetStream();
xwb.Save(stream);
8. Load sheet1.xml file in to the worksheet part
XmlDocument xsheet=new XmlDocument();
xsheet.Load(@"..\..\sheet1.xml");
Stream stream1 = wsPart.GetStream();
xsheet.Save(stream1);
6. Close the document handler
spDoc.Close();