nissl-lab / npoi

a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.
Apache License 2.0
5.74k stars 1.44k forks source link

excel file damaged after adding images and saving #1352

Closed rick-yang1987 closed 2 months ago

rick-yang1987 commented 6 months ago

NPOI Version

2.6.2

File Type

Upload the Excel File

项目资金预算(原文件).xlsx

Reproduce Steps

1、open file 2、add image 3、save

Issue Description

tonyqus commented 4 months ago

Can you share the code of how you add the image?

rick-yang1987 commented 3 months ago
    static Boolean InsertImage(XSSFWorkbook workbook, ISheet sheet, byte[] imageData, int row, int column, int endRows, int endCols)
    {
        try
        {
            XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch();
            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, column, row, endCols + 1, endRows + 1);
            anchor.AnchorType = AnchorType.MoveAndResize;

            int pictureIndex = workbook.AddPicture(imageData, PictureType.BMP);
            XSSFPicture picture = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIndex);
            picture.LineStyle = LineStyle.None;
        }
        catch(System.Exception ex)
        {
            return false;
        }

        return true;
    }