简体   繁体   中英

Why does my WorkbookView sequence keep returning “null” value with OpenXml?

I have created a download button in C#/asp.net, which takes a GridView, converts it to a data table, and then stores it into a.xlsx file. What I want to do after is be able to change the active tab of the spreadsheet I created.

Here is the code below:

 protected void downloadBtn_Click(object sender, EventArgs e)
    {

        using (var spreadSheet = SpreadsheetDocument.Create(Server.MapPath("~/Downloads/TestSheet.xlsx"), DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
        {
            WorkbookPart workbookPart = spreadSheet.AddWorkbookPart();
            workbookPart.Workbook = new Workbook();

            WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());

            //Fine up to this point

            spreadSheet.WorkbookPart.Workbook.Sheets = new Sheets();

            DataTable table = new DataTable();
            //Converts GridView into Data Table **
            for (int i = 0; i < gvEmployee.HeaderRow.Cells.Count - 1; i++)
            {

                table.Columns.Add(gvEmployee.HeaderRow.Cells[i + 1].Text);
            }
            // fill rows     
            for (int i = 0; i < gvEmployee.Rows.Count; i++)
            {
                DataRow dr = table.NewRow();
                for (int j = 0; j < gvEmployee.Columns.Count - 1; j++)
                {
                    dr[j] = gvEmployee.Rows[i].Cells[j + 1].Text;
                }
                table.Rows.Add(dr);

            }

            var sheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
            var sheetData = new SheetData();
            sheetPart.Worksheet = new Worksheet(sheetData);

            Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
            string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(sheetPart);

            uint sheetId = 1;
            if (sheets.Elements<Sheet>().Count() > 0)
            {
                sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
            }

            Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = "TestSheet" };
            sheets.Append(sheet);

            Row headerRow = new Row();
            List<String> columns = new List<string>();
            foreach (DataColumn column in table.Columns)
            {

                columns.Add(column.ColumnName);

                Cell cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue(column.ColumnName);
                headerRow.AppendChild(cell);
            }


            sheetData.AppendChild(headerRow);
            foreach (DataRow dsrow in table.Rows)
            {
                Row newRow = new Row();
                foreach (String col in columns)
                {
                    Cell cell = new Cell();
                    cell.DataType = CellValues.String;
                    cell.CellValue = new CellValue(dsrow[col].ToString()); //
                    newRow.AppendChild(cell);
                }

                sheetData.AppendChild(newRow);
            }


            Sheet sheet2 = new Sheet() { Id = spreadSheet.WorkbookPart.GetIdOfPart(sheetPart), SheetId = 2, Name = "AdditionalSheet" };
            sheets.Append(sheet2);

            var sheetIndex = workbookPart.Workbook.Descendants<Sheet>().ToList().IndexOf(sheet2);
            WorkbookView workbookView = workbookPart.Workbook.Descendants<WorkbookView>().FirstOrDefault(); //new WorkbookView();
            workbookView.ActiveTab = Convert.ToUInt32(sheetIndex);

            workbookPart.Workbook.Save();
            spreadSheet.Close();

        }
    }

When I try to run this code, it throws an error on the "workbookView.ActiveTab" at the last few lines stating

System.NullReferenceException: 'Object reference not set to an instance of an object.'

workbookView was null.

Any ideas as to why its doing this?

Okay, I just figured out what was wrong, there was no WorkbookView initialized, as I thought it thought it didn't need to be. But you have to actually make a WorkbookView of your workbook before you can change it. I just needed this one line:

            workbookPart.Workbook.Append(new BookViews(new WorkbookView()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM