Hello Everyone,
I am new to c# and am trying to use Open XML to pull data from a SQL server into a spreadsheet. I followed some examples I found online but had to alter them to fit the test scenario I have set up and have run into an error I am not sure how to debug.

I am receiving error code CS0120, "An object reference is required for the non-static field, method or property 'Program.CreateContentRow(int, int, string, string, string)'"

I tried adding code along the lines of "Row contentRow = new Row()", because that is pretty much the extent of what my current knowledge is regarding object references, but that does not fix the problem. Is the issue with my code that I need to pull the code from the static main method? Any help or information would be greatly appreciated. I am trying to understand what I did wrong here so I know how to do things differently in the future.

Thanks.

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Spreadsheet;
    using System.IO;

    namespace ExcellTakeTwo
    {
    class Program
    {
        private const string ExcelTemplateFile = @"Template.xlsx";
        private const string GeneratedExcelFile = @"Security.xlsx";
        string[] headerColumns = new string[] { "A", "B", "C", "D" };
        static void Main(string[] args)
        {
            // Make a copy of template file
            File.Copy(ExcelTemplateFile, GeneratedExcelFile, true); 

            //Open the copied template workbook           
            using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(GeneratedExcelFile, true))
            {
                // Access the main workbook part with all of the references
                WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;

                // Grab the first worksheet
                WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();

                // SheetData will contain all the data
                SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

                //Connect to the database Security
                WyattsLinqDataContext wyattsLinqDataContext = new WyattsLinqDataContext();

                // Data starts on row 2
                int index = 2;

                // Select * from Security table
                var securityQuery =
                    from Security
                    in wyattsLinqDataContext.Securities
                    select Security;

                // For each row in database add a row to spreadsheet
                foreach (var item in securityQuery)
                {
                    int personId = item.PersonID;
                    string lastName = item.LastName;
                    string firstName = item.FirstName;
                    string userPass = item.Password;

                    //Add a new row                    
                    Row contentRow = CreateContentRow(index, personId, lastName, firstName, userPass);
                    index++;

                    // Append new row to data sheet
                    sheetData.AppendChild(contentRow);                    
                }  

            }

        }
        Row CreateContentRow(int index, int personId, string lastName, string firstName, string userPass)
        {
            // Create new row
            Row row = new Row();

            row.RowIndex = (UInt32)index;

            // first cell is a text cell, so create it and append it

            Cell firstCell = CreateTextCell(headerColumns[0], personId.ToString(), index);

            row.AppendChild(firstCell);

            // Create cells that contain data

            for (int i=1; i < headerColumns.Length; i++)
            {
                Cell cell = new Cell();

                cell.CellReference = headerColumns[i] + index;

                CellValue cellValue = new CellValue();

                if (i == 1)
                {
                    cellValue.Text = lastName.ToString();
                }
                else if (i == 2)
                {
                    cellValue.Text = firstName.ToString();
                }
                else
                {
                    cellValue.Text = userPass.ToString();
                }
                cell.AppendChild(cellValue);
                row.AppendChild(cell);
            }
            return row;
        }
        Cell CreateTextCell(string header, string text, int index)
        {
            // Create new inline string cell
            Cell cell = new Cell();

            cell.DataType = CellValues.InlineString;

            cell.CellReference = header + index;

            // Add text to text cell
            InlineString inlineString = new InlineString();

            Text newText = new Text();

            newText.Text = text;

            inlineString.AppendChild(newText);
            cell.AppendChild(inlineString);

            return cell;
        }
    }
    }

Dani AI

Generated

Short answer: the CS0120 error happens because Main is static and it calls instance helpers. In your code the call to CreateContentRow(...) is coming from a static method without an object, so the compiler complains that an object reference is required.

Two quick, correct options (tradeoffs noted):

  • Call the helper on a Program instance. For a minimal fix, create an instance inside Main and call the instance method:
var exporter = new Program();
Row contentRow = exporter.CreateContentRow(index, personId, lastName, firstName, userPass);

This preserves instance fields like headerColumns and is the least-invasive change.

  • Follow and make the helper methods static. If you choose that, also either make any fields they use static (for example, a static readonly headers array) or pass those values into the static methods. Static methods cannot access instance fields.

Design note: for cleaner code, extract the OpenXML/export logic into a dedicated class (for example ExcelExporter) whose constructor takes any dependencies (template path, header list, DB context) and exposes instance methods. That makes testing easier and avoids mixing static state into Program.

Debug tips: recompile after each small change and read the compiler line number for CS0120. If the template file or OpenXML types cause further compile/runtime issues, address those separately once the static/instance mismatch is fixed.

Try declaring your methods as static:

static Row CreateContentRow(int index, int personId, string lastName, string firstName, string userPass)

static Cell CreateTextCell(string header, string text, int index)
commented: This lead me to a working solution! Thank you so much! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.