'The file is corrupt and cannot be opened' OpenXML

余生颓废 提交于 2019-12-23 13:58:17

问题


I got that code from OpenXML sdk and instead of SpreadsheetDocument.Create, I used SpreadsheetDocument.Open

This code is working and add an image in .xlsx, after image added to the file. I open the file which shows ->

The file is corrupt and cannot be opened

If you want more details Please! let me know.

Reference URL -> https://code.msdn.microsoft.com/office/How-to-insert-image-into-93964561

Thanks for the help!

    /// <summary>
    /// add sheet in xlsx then add image into it.
    /// </summary>
    /// <param name="sFile"></param>
    /// <param name="imageFileName"></param>
    public void InsertimginExcel(string sFile, string imageFileName)
    {
        try
        {
            // Create a spreadsheet document by supplying the filepath. 
            using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
                Open(sFile, true))
            {

                // Add a WorkbookPart to the document. 
                //WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
                //workbookpart.Workbook = new Workbook();

                // Add a WorksheetPart to the WorkbookPart. 
                WorksheetPart worksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet(new SheetData());

                // Add Sheets to the Workbook. 
                Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
                    AppendChild<Sheets>(new Sheets());

                // Append a new worksheet and associate it with the workbook. 
                Sheet sheet = new Sheet()
                {
                    Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
                    SheetId = 1,
                    Name = "mySheet"
                };
                sheets.Append(sheet);

                var drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();

                if (!worksheetPart.Worksheet.ChildElements.OfType<DocumentFormat.OpenXml.Spreadsheet.Drawing>().Any())
                {
                    worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing { Id = worksheetPart.GetIdOfPart(drawingsPart) });
                }

                if (drawingsPart.WorksheetDrawing == null)
                {
                    drawingsPart.WorksheetDrawing = new WorksheetDrawing();
                }

                var worksheetDrawing = drawingsPart.WorksheetDrawing;

                var imagePart = drawingsPart.AddImagePart(ImagePartType.Jpeg);

                using (var stream = new FileStream(imageFileName, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }

                Bitmap bm = new Bitmap(imageFileName);
                DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
                var extentsCx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
                var extentsCy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
                bm.Dispose();

                var colOffset = 0;
                var rowOffset = 0;
                int colNumber = 5;
                int rowNumber = 10;

                var nvps = worksheetDrawing.Descendants<Xdr.NonVisualDrawingProperties>();
                var nvpId = nvps.Count() > 0 ?
                    (UInt32Value)worksheetDrawing.Descendants<Xdr.NonVisualDrawingProperties>().Max(p => p.Id.Value) + 1 :
                    1U;

                var oneCellAnchor = new Xdr.OneCellAnchor(
                    new Xdr.FromMarker
                    {
                        ColumnId = new Xdr.ColumnId((colNumber - 1).ToString()),
                        RowId = new Xdr.RowId((rowNumber - 1).ToString()),
                        ColumnOffset = new Xdr.ColumnOffset(colOffset.ToString()),
                        RowOffset = new Xdr.RowOffset(rowOffset.ToString())
                    },
                    new Xdr.Extent { Cx = extentsCx, Cy = extentsCy },
                    new Xdr.Picture(
                        new Xdr.NonVisualPictureProperties(
                            new Xdr.NonVisualDrawingProperties { Id = nvpId, Name = "Picture " + nvpId, Description = imageFileName },
                            new Xdr.NonVisualPictureDrawingProperties(new A.PictureLocks { NoChangeAspect = true })
                        ),
                        new Xdr.BlipFill(
                            new A.Blip { Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = A.BlipCompressionValues.Print },
                            new A.Stretch(new A.FillRectangle())
                        ),
                        new Xdr.ShapeProperties(
                            new A.Transform2D(
                                new A.Offset { X = 0, Y = 0 },
                                new A.Extents { Cx = extentsCx, Cy = extentsCy }
                            ),
                            new A.PresetGeometry { Preset = A.ShapeTypeValues.Rectangle }
                        )
                    ),
                    new Xdr.ClientData()
                );

                worksheetDrawing.Append(oneCellAnchor);

                //workbookpart.Workbook.Save();

                // Close the document. 
                spreadsheetDocument.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            //log.Error("error occur while creating sheet and adding image --> " + ex.Message.ToString());
        }
    }

回答1:


Not sure how many workbookparts and worksheetparts a xlsx file can handle and if the SheetId must be document unique for all Sheets. Try changing the Id to e.g. 5 if that does not help: do not create a new workbookpart for the sheet, use existig one, if possible.




回答2:


The file is corrupt and cannot be opened

Uncheck all the options under Protected View and confirm by pressing OK.

Restart Excel and try to open the broken Excel documents.

Ref: https://answers.microsoft.com/en-us/office/forum/office_2010-excel/the-file-is-corrupt-and-cannot-be-opened-error-on/93af59c1-946c-4f5f-83c1-bd6f58dbd94f


If that doesn't work, typically when you create XSLX files and there is an error, you see this:

Can you check your Temporary Internet Files for the log. The log file should have info on what is malformed. Please update your question with any additional info.



来源:https://stackoverflow.com/questions/49727901/the-file-is-corrupt-and-cannot-be-opened-openxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!