OpenXML和WebAPI C#的奇怪行为

时间:2018-08-08 22:09:42

标签: c# asp.net-web-api openxml

我在生产服务器中有一个Web应用程序,该应用程序会创建一个“ xlsx”文件,并用数据填充并将其下载到用户桌面。

它工作正常,但有时在PRD服务器中会引发以下错误:

对象引用未设置为对象的实例。

据我所见,问题在WorkBookPart中。

有什么想法吗?

谢谢

这是我的代码:

    Random random = new Random();
        int randomNumber = random.Next(0, 10000);


        string ExcelFileName = "XXXXXXXXXXXXXX" + randomNumber.ToString() + ".xlsx";





        using (SpreadsheetDocument spreedDoc = SpreadsheetDocument.Create(ExcelFileName,DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
        {
            //WorkbookPart wbPart = spreedDoc.WorkbookPart;
           // if (wbPart == null)
           // {
                WorkbookPart wbPart = spreedDoc.AddWorkbookPart();
                wbPart.Workbook = new Workbook();
           // }

            string sheetName = "Data";
            WorksheetPart worksheetPart = null;
            worksheetPart = wbPart.AddNewPart<WorksheetPart>();
            var sheetData = new SheetData();

            worksheetPart.Worksheet = new Worksheet(sheetData);

            if (wbPart.Workbook.Sheets == null)
            {
                wbPart.Workbook.AppendChild<Sheets>(new Sheets());
            }

            var sheet = new Sheet()
            {
                Id = wbPart.GetIdOfPart(worksheetPart),
                SheetId = 1,
                Name = sheetName
            };

            var workingSheet = ((WorksheetPart)wbPart.GetPartById(sheet.Id)).Worksheet;

            Row _rowheaders = new Row();

            _rowheaders.Append(XXXXXXXXXXXXXXXXXXX);

            sheetData.Append(_rowheaders);

            foreach (var item in _datacontext.DataList)
            {
                Row _row = new Row();

                _row.Append(
                    XXXXXXXXXXXXXXXXXXX
                    );


                sheetData.Append(_row);
            }

            wbPart.Workbook.Sheets.AppendChild(sheet);
            wbPart.Workbook.Save();
        }

        return ExcelFileName;
    }

0 个答案:

没有答案