1

I'm fairly new to creating Excel spreadsheets in C# and I'm looking for advice. I've spent 2 or 3 days now looking through documentation and blogs etc but I cannot seem to find an answer to a common task.

I need to insert a text value into a specific worksheet. I cant easily post my code at the moment but it appears to be an issue with every example I've seen of the definition of a sheet, it always gets the first child.

I need to iterate through all sheets and dependant on the sheet name then go and insert a value.

I.e. If the sheet name = "testA" then write TestA, if the sheet name = "testB" then write "TestB".

Currently I can insert a value for the workbook but it inserts the same value for every sheet.

Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();

[Microsoft documentation] (https://learn.microsoft.com/en-us/office/open-xml/how-to-insert-text-into-a-cell-in-a-spreadsheet)

Please note I'm not just giving up on this I've just reached a bit of a wall with it and need some pointers.

Many Thanks, J

Namespaces I'm using:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;


private void btnExport_Click(object sender, EventArgs e)
    {

        //Using Microsofts Interop class to create Excel files gives mixed resuts and requires excel to be installed.
        // This uses OpenXML library to achieve this and doesnt require excel to be installed: https://medium.com/swlh/openxml-sdk-brief-guide-c-7099e2391059


        string filepath = "Test.xlsx";
        // Create a spreadsheet document by supplying the filepath.
        // By default, AutoSave = true, Editable = true, and Type = xlsx.
        SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
            Create(filepath, SpreadsheetDocumentType.Workbook);

        // Add a WorkbookPart to the document.
        WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
        workbookpart.Workbook = new Workbook();

        // Add a WorksheetPart to the WorkbookPart.
        WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
        worksheetPart.Worksheet = new Worksheet(new SheetData());

        // Add Sheets to the Workbook.
        Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
            AppendChild<Sheets>(new Sheets());

        // Append a new worksheet and associate it with the workbook.
        Sheet sheetOne = new Sheet()
        {
            Id = spreadsheetDocument.WorkbookPart.
            GetIdOfPart(worksheetPart),
            SheetId = 1,
            Name = "Sheet1"
        };

        Sheet sheetTwo= new Sheet()
        {
            Id = spreadsheetDocument.WorkbookPart.
            GetIdOfPart(worksheetPart),
            SheetId = 2,
            Name = "Sheet2"
        };

        Sheet sheetParameters = new Sheet()
        {
            Id = spreadsheetDocument.WorkbookPart.
            GetIdOfPart(worksheetPart),
            SheetId = 3,
            Name = "Parameters"
        };

        Sheet sheetFour= new Sheet()
        {
            Id = spreadsheetDocument.WorkbookPart.
            GetIdOfPart(worksheetPart),
            SheetId = 4,
            Name = "Sheet4"
        };

        Sheet sheetFive= new Sheet()
        {
            Id = spreadsheetDocument.WorkbookPart.
            GetIdOfPart(worksheetPart),
            SheetId = 5,
            Name = "Sheet5"
        };

        

        sheets.Append(sheetOne);
        sheets.Append(sheetTwo);
        sheets.Append(sheetParameters);
        sheets.Append(sheetFour);
        sheets.Append(sheetFive);

        
        
        workbookpart.Workbook.Save();
        // Close the document.

        
        spreadsheetDocument.Close();

        //InsertTextExistingExcel(filepath, "test1", "A", 1, "Parameters");
        InsertInSheet(filepath, "test1", "A", 1, "Parameters");
        //Any of these lists empty?

       


    }

    public static void InsertInSheet(string filePath, string value, string columnName, uint rowIndex, string sheetName)
    {
        using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(filePath, true))
        {
            getSheetDetails(spreadSheet);
        }
    }



  

    //work here
    public static void getSheetDetails(SpreadsheetDocument doc)
    {
        WorksheetPart worksheetPart;
        //iterate through sheets
        foreach (Sheet sheetDetail in doc.WorkbookPart.Workbook.Sheets)
        {
            if (sheetDetail.Name == "Parameters")
            {
                //each sheet has a worksheetPart
                worksheetPart = (WorksheetPart)doc.WorkbookPart.GetPartById(sheetDetail.Id);
                Cell cell = InsertCellInWorksheet("A", 1, worksheetPart);

                
                cell.CellValue = new CellValue("test");
                cell.DataType = new EnumValue<CellValues>(CellValues.String);

                worksheetPart.Worksheet.Save();


            }
            

        }
    }






    private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
    {
        //fix earlier worksheetPart only has a count of 1
        Worksheet worksheet = worksheetPart.Worksheet;
        //fix this to point to sheet
        //SheetData sheetData = worksheet.Descendants<SheetData>();
        SheetData sheetData = worksheet.GetFirstChild<SheetData>();

        MessageBox.Show(sheetData.InnerXml.ToString());




        string cellReference = columnName + rowIndex;

        Row row;
        if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
        {
            row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
        }
        else
        {
            row = new Row() { RowIndex = rowIndex };
            sheetData.Append(row);
        }

        Cell refCell = row.Descendants<Cell>().LastOrDefault();

        Cell newCell = new Cell() { CellReference = cellReference };
        row.InsertAfter(newCell, refCell);

        worksheet.Save();
        return newCell;

    }
John Doe
  • 29
  • 1
  • 8
  • So what did you try, where did you fail? You only provide a single line of code, how are we supposed to tell you what you are doing wrong. – CSharpie Nov 27 '20 at 12:42
  • 1
    Just added the code, apologies its a working progress and I didnt want to expose my bad programming haha. – John Doe Nov 27 '20 at 14:26
  • Currently this writes out the same value to every sheet. So it doesn't fail its just not working as I expected in that I need it to insert a specific string into a specific worksheet. – John Doe Nov 27 '20 at 14:32
  • @JohnDoe Did you find solution to this? I am also trying to write to different sheets but having no success. Posted a question here: https://stackoverflow.com/questions/73709414/write-to-excel-sheet-using-openxml-c-sharp – Varin Sep 14 '22 at 17:08
  • @Varin Afraid not - I was making a utility to convert RDL (SSRS Report files) to an Excel document so it would list all of the data sources and SQL for all RDL files in bulk. We ended up going down a different reporting solution at work so I never finished it. – John Doe Nov 22 '22 at 09:24

0 Answers0