4

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());
        }
    }
Utkarsh Dubey
  • 703
  • 11
  • 31
  • Is this an error when opening with excel? If not, then why tag excel? – Solar Mike Apr 09 '18 at 08:35
  • yes, this is error when I am trying to open excel file after making the changes in excel file using above mention code. –  Apr 09 '18 at 08:47
  • First thing I would check is whether the generated .xlsx is well formed and valid XML. https://www.xmlvalidation.com/ – Georg Patscheider Apr 11 '18 at 13:06
  • Are you tied to OpenXML SDK or free to use other Frameworks/Wrapper, which might make it easier to create/insert an Image to a xlsx file. Examples would be EPPlus https://stackoverflow.com/questions/11588704/adding-images-into-excel-using-epplus#11880491 or ClosedXML https://github.com/closedxml/closedxml/wiki/How-can-I-insert-an-image ;These arose, because nobody whats to work with OpenXML SDK directly if not necessary – FrankM Apr 13 '18 at 12:32
  • 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. – FrankM Apr 13 '18 at 12:41
  • Thanks a lot @FrankM for your last comment it really help. –  Apr 14 '18 at 07:12
  • @FrankM, Please! put your comment in the answer so I can assign you a bounty. – Utkarsh Dubey Apr 16 '18 at 04:12
  • @UtkarshDubey: Done; JohnDoe: I am happy, my hints could point you in the right direction :) – FrankM Apr 16 '18 at 14:51

2 Answers2

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.

FrankM
  • 541
  • 3
  • 15
0

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.

enter image description here

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:

enter image description here

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.

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • Could you please confirm you checked if the log files exist? Also, when you ask questions on [so] include your research, what you've tried and the results. This helps people not suggest what you've already tried. Please update your question. – Jeremy Thompson Apr 13 '18 at 23:30