I managed to create a workbook programmatically with the only input being an arbitrarily chosen excel file path. I encounter a System.NullReferenceException when trying to create the Sheet object. I suspect that this is because my workbook doesn't have any sheets. How can I debug this?
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;
using System.IO;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using System.Reflection;
using System.Linq;
namespace ConsoleApp35
{
class Program
{
static void Main(string[] args)
{
{
SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Create(@"C:\________________.xlsx", SpreadsheetDocumentType.Workbook);
spreadsheetDocument.AddWorkbookPart();
{
// Add a WorksheetPart.
WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
// Create Sheets object.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = spreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart);
// Create a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "mySheet" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
}
Console.WriteLine("All done.");
Console.ReadKey();
}
}
}
}