Master
Master

Reputation: 2959

Insert image in xls file using npoi api?

I want to insert images in excel workbook's sheet. My code for inserting an image is here:

                    ISheet sheet = templateWorkbook.GetSheet(sheetName);

                    HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                    //IDrawing patriarch = (IDrawing)sheet.CreateDrawingPatriarch();
                    //HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
                            start.Col, start.Row, end.Col, end.Row);
                    anchor.AnchorType = 2;
                    int pictureIdx = 0;
                    using (FileStream fs = new FileStream(f.GetServerPathOfFile(imagePath), FileMode.Open))
                    {
                        byte[] bytes = new byte[fs.Length];
                        fs.Write(bytes, 0, (int)fs.Length);
                        pictureIdx = templateWorkbook.AddPicture(bytes, PictureType.JPEG);
                    }
                    IPicture picture = patriarch.CreatePicture(anchor, pictureIdx);

I do not know where I am getting it wrong. The code runs fine without any error/exception.

Upvotes: 0

Views: 4136

Answers (2)

Kokia
Kokia

Reputation: 1

I think I know the bug. If you know Chinese,

你需要先把图片加进去在描点 。

Just put

using (FileStream fs = new FileStream(f.GetServerPathOfFile(imagePath), FileMode.Open))
{
    byte[] bytes = new byte[fs.Length];
    fs.Write(bytes, 0, (int)fs.Length);
    pictureIdx = templateWorkbook.AddPicture(bytes, PictureType.JPEG);
}

before

HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, 
  start.Col, start.Row, end.Col, end.Row);
anchor.AnchorType = 2;

Upvotes: 0

Ender
Ender

Reputation: 11

If problem are still actual - picture.Resize(); could help

Upvotes: 1

Related Questions