I am trying to write to individual sheets in an .xlxs
file. I have the following piece of code but it writes to all the sheets even if I am adding sheetData
to a designated sheet.
private void WriteToSheet(string sheetName, string filePath)
{
using var SpreadsheetDocument doc = SpreadsheetDocument.Open(filePath, true);
var wbPart = doc.WorkbookPart;
if (wbPart == null)
return;
var sheets = wbPart.Workbook.Descendants<Sheet>();
var sheet = sheets.SingleOrDefault((s) => s.Name.Equals(sheetName));
if (sheet == null)
return;
var worksheet = ((WorksheetPart)wbPart?.GetPartById(sheet.Id)).Worksheet;
var sheetData = worksheet.AppendChild(new SheetData());
WriteTableHeader(sheetData);
WriteTableData(sheetData);
worksheet.Save();
}
private void WriteTableHeader(SheetData sheetData)
{
var row = sheetData.AppendChild(new Row());
row.Height = 30;
row.AppendChild(new Cell() { CellValue = new CellValue("ID"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("File"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Entity"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Form"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Year"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Group"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Line"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Description"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Value 1"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Value 2"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Difference"), DataType = CellValues.String, StyleIndex = 8 });
row.AppendChild(new Cell() { CellValue = new CellValue("Order"), DataType = CellValues.String, StyleIndex = 8 });
}