使用npoi api在xls文件中插入图像?

时间:2012-12-19 06:00:34

标签: c# excel xls npoi

我想在excel工作簿的工作表中插入图像。我插入图片的代码在这里:

                    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);

我不知道我在哪里弄错了。代码运行正常,没有任何错误/异常。

2 个答案:

答案 0 :(得分:0)

如果问题仍然存在 - picture.Resize();可以提供帮助

答案 1 :(得分: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);
}

之前

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