生成excel时出错

时间:2018-03-20 14:06:59

标签: c# openxml

当我尝试使用4个值生成新的excel文件时,我在C#中遇到了问题。当我尝试打开文件时收到错误告诉我: excel无法打开文件,因为文件格式或文件扩展名无效

当我尝试调试它时,我注意到输出是trowing: 系统无效操作异常,我不知道如何解决此问题。我只想生成内部有一些值的excel文件(稍后我将填充插入我的值)。现在我只是想创建一个没有被破坏的excel文件。

    [HttpPost]
    public HttpResponseMessage PrintDevices()
    {

        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        using (MemoryStream output = new MemoryStream())
        {


            using (SpreadsheetDocument document = SpreadsheetDocument.Create(output, SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

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

                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

                Sheet sheet = new Sheet()
                {
                    Id = workbookPart.GetIdOfPart(worksheetPart),
                    SheetId = 1,
                    Name = "Testing"
                };

                sheets.Append(sheet);

                workbookPart.Workbook.Save();


                SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

                // Constructing header
                Row row = new Row();

                row.Append(
                    ConstructCell("Id", CellValues.String),
                    ConstructCell("Name", CellValues.String),
                    ConstructCell("Birth Date", CellValues.String),
                    ConstructCell("Salary", CellValues.String));

                // Insert the header row to the Sheet Data
                sheetData.AppendChild(row);

                // Inserting each employee


                worksheetPart.Worksheet.Save();
            }
        }

         Cell ConstructCell(string value, CellValues dataType)
        {
            return new Cell()
            {
                CellValue = new CellValue(value),
                DataType = new EnumValue<CellValues>(dataType)
            };
        }

        return response;
    }

0 个答案:

没有答案