OpenXML spreadsheet created in .NET won't open in iPad

后端 未结 5 2028
梦毁少年i
梦毁少年i 2020-12-16 05:59

I am trying to generate a spreadsheet in .NET which will be opened by my manager on his iPad when he\'s out of the office.

The spreadsheet opens fine on a Windows PC

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 06:29

    I have also been struggling with a problem similar to this for a while. I finally came up with a solution that works. This is the code I wrote to fix the problem

            // Add a new worksheet part to the workbook.
            WorksheetPart newWorksheetPart = _document.WorkbookPart.AddNewPart();
            newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());
    
            Sheets sheets = _document.WorkbookPart.Workbook.GetFirstChild();
            string relationshipId = _document.WorkbookPart.GetIdOfPart(newWorksheetPart);
    
            //This bit is required for iPad to be able to read the sheets inside the xlsx file. The file will still work fine in Excel
            string relationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet";
            _document.Package.GetPart(_document.WorkbookPart.Uri).CreateRelationship(new Uri(newWorksheetPart.Uri.OriginalString.Replace("/xl/", String.Empty).Trim(), UriKind.Relative), TargetMode.Internal, relationshipType);
            _document.Package.GetPart(_document.WorkbookPart.Uri).DeleteRelationship(relationshipId);
            PackageRelationshipCollection sheetRelationships = _document.Package.GetPart(_document.WorkbookPart.Uri).GetRelationshipsByType(relationshipType);
    
            relationshipId = sheetRelationships.Where(f => f.TargetUri.OriginalString == newWorksheetPart.Uri.OriginalString.Replace("/xl/", String.Empty).Trim()).Single().Id;
    
    
            // Get a unique ID for the new sheet.
            uint sheetId = 1;
            if (sheets.Elements().Count() > 0)
                sheetId = sheets.Elements().Max(s => s.SheetId.Value) + 1;
    
            // Append the new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
            sheets.Append(sheet);
    
            _worksheets.Add(new Worksheet(newWorksheetPart.Worksheet, sheetId));
    

    _document and _worksheets, are private variables in my solution class.

提交回复
热议问题