public void CreateExcel(string xlFilePath) { FileInfo xlFileInfo = new FileInfo(xlFilePath); if (xlFileInfo.Exists) { xlFileInfo.Delete(); } xlDoc = SpreadsheetDocument.Create(xlFilePath, SpreadsheetDocumentType.Workbook); wbPart = xlDoc.AddWorkbookPart(); wbPart.Workbook = new Workbook(); }
/// <summary> /// Creates the workbook /// </summary> /// <returns>Spreadsheet created</returns> public static DocumentFormat.OpenXml.Packaging.SpreadsheetDocument CreateWorkbook(string fileName) { DocumentFormat.OpenXml.Packaging.SpreadsheetDocument spreadSheet = null; DocumentFormat.OpenXml.Packaging.SharedStringTablePart sharedStringTablePart; DocumentFormat.OpenXml.Packaging.WorkbookStylesPart workbookStylesPart; try { // Create the Excel workbook spreadSheet = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Create(fileName, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, false); // Create the parts and the corresponding objects // Workbook spreadSheet.AddWorkbookPart(); spreadSheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook(); spreadSheet.WorkbookPart.Workbook.Save(); // Shared string table sharedStringTablePart = spreadSheet.WorkbookPart.AddNewPart <DocumentFormat.OpenXml.Packaging.SharedStringTablePart>(); sharedStringTablePart.SharedStringTable = new DocumentFormat.OpenXml.Spreadsheet.SharedStringTable(); sharedStringTablePart.SharedStringTable.Save(); // Sheets collection spreadSheet.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets(); spreadSheet.WorkbookPart.Workbook.Save(); // Stylesheet workbookStylesPart = spreadSheet.WorkbookPart.AddNewPart <DocumentFormat.OpenXml.Packaging.WorkbookStylesPart>(); workbookStylesPart.Stylesheet = new DocumentFormat.OpenXml.Spreadsheet.Stylesheet(); workbookStylesPart.Stylesheet.Save(); } catch (System.Exception exception) { // System.Windows.MessageBox.Show(exception.Message, "Excel OpenXML basics", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Hand); throw exception; } return(spreadSheet); }