如何使用 npoi 将图像放置在一个单元格中

发布于 2024-11-02 06:20:17 字数 1324 浏览 6 评论 0原文

我正在使用 npoi 生成 Excel 文档。我需要将图像添加到单元格中。使用以下代码我可以将图像插入到我的文档中。然而图像跨越了许多单元格。我怎样才能确保图像正好适合一次单元格内。

public ActionResult NPOICreate()
{
    try
    {
        FileStream fs = new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.ReadWrite);
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
        var sheet = templateWorkbook.GetSheet("Sheet1");
        var patriarch = sheet.CreateDrawingPatriarch();
        HSSFClientAnchor anchor;
        anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short)6, 5);
        anchor.AnchorType = 2;
        var picture = patriarch.CreatePicture(anchor, LoadImage(@"D:\dev\Website/HumpbackWhale.jpg", templateWorkbook));
        picture.Resize();
        picture.LineStyle = HSSFPicture.LINESTYLE_DASHDOTGEL;
        sheet.ForceFormulaRecalculation = true;
        MemoryStream ms = new MemoryStream();
        templateWorkbook.Write(ms);
        TempData["Message"] = "Excel report created successfully!";
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch (Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }

}

I'm using npoi to generate excel docs. I have a requirement to add images to cells. Using the following code i can insert images into my doc. However the image span many cells. How can i ensure that the image just fits inside once cell.

public ActionResult NPOICreate()
{
    try
    {
        FileStream fs = new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.ReadWrite);
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
        var sheet = templateWorkbook.GetSheet("Sheet1");
        var patriarch = sheet.CreateDrawingPatriarch();
        HSSFClientAnchor anchor;
        anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short)6, 5);
        anchor.AnchorType = 2;
        var picture = patriarch.CreatePicture(anchor, LoadImage(@"D:\dev\Website/HumpbackWhale.jpg", templateWorkbook));
        picture.Resize();
        picture.LineStyle = HSSFPicture.LINESTYLE_DASHDOTGEL;
        sheet.ForceFormulaRecalculation = true;
        MemoryStream ms = new MemoryStream();
        templateWorkbook.Write(ms);
        TempData["Message"] = "Excel report created successfully!";
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch (Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

向日葵 2024-11-09 06:20:17

据我所知,无法将图像对象分配给 Excel 中的特定单元格
这不是 POI/NPOI 的限制,而是 Excel 的工作方式:插入到电子表格中的图片只是浮动(在电子表格网格本身上)...< br>
最好的情况是,通过确保细胞的大小和位置与图片完美匹配,可以让人相信它在细胞中。图片有一个属性(请参阅“设置图片格式”对话框,属性部分,我确信也可以通过 POI 访问),它允许指定图片是否会根据其周围的行/单元格上的操作移动和/或调整自身大小,但最终,图片最多仍然是一个与单元格关系非常松散的浮动对象

将图片分配给单元格的一个常见技巧是通过注释的方式。然后,图片会更正式地绑定到单元格,但它不会显示为内容,而是显示为评论数据。
例如,请参阅此秘诀。这个想法是使用评论的背景作为具有特殊填充效果的颜色,这是我们希望与单元格关联的图片。同样,必须有一种方法可以通过 NPOI 以编程方式实现这一目标,但我无法直接证实这一点。

To the best of my knowledge, it isn't possible to assign an image object to a particular cell within Excel.
This is not a limitation of POI/NPOI, but rather the way Excel works: Pictures inserted into a spreadsheet just float (over the spreadsheet grid per se)...
At best one can make believe it is in the cell by ensuring that the size and position of the cell and of the picture match perfectly. There is a property of the picture (See "Format Picture" dialog, Properties section, also accessible through POI I'm sure) which allows to specify whether the picture will move and/or resize itself following actions on rows/cells surrounding it, but in the end, pictures remain a floating object very loosely related to a cell at best.

A common trick to assign a picture to a cell is by way of comments. The picture is then more formally bound to the cell but it is not shown as content but rather a comment data.
See for example this recipe. The idea is to use the background of the comment to be a color with a special fill effect which is the picture we wish to associate with the cell. Here again, there's got to be a way of achieving this programmatically with NPOI, but I cannot affirm this firsthand.

紫﹏色ふ单纯 2024-11-09 06:20:17

您可以尝试以下操作:

您看到该属性,anchor.AnchorType = 2;?尝试将其设置为 0 或 3,看看会发生什么。在 C# (NPOI) 端口中,0 将使用选项 0 将图像放入一个单元格中。

下面是一些示例代码(在 C# Asp.net 项目中使用,以防有人在这里闲逛需要它):

HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet1 = hssfworkbook.CreateSheet(sheetName);
//map the path to the img folder
string imagesPath = System.IO.Path.Combine(Server.MapPath("~"), "img");
//grab the image file
imagesPath = System.IO.Path.Combine(imagesPath, "image.png");
//create an image from the path
System.Drawing.Image image = System.Drawing.Image.FromFile(imagesPath);
MemoryStream ms = new MemoryStream();
//pull the memory stream from the image (I need this for the byte array later)
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//the drawing patriarch will hold the anchor and the master information
HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();
//store the coordinates of which cell and where in the cell the image goes
HSSFClientAnchor anchor = new HSSFClientAnchor(20, 0, 40, 20, 3, 10, 4, 11);
//types are 0, 2, and 3. 0 resizes within the cell, 2 doesn't
anchor.AnchorType = 2;
//add the byte array and encode it for the excel file
int index = hssfworkbook.AddPicture(ms.ToArray(), HSSFPicture.PICTURE_TYPE_PNG);
HSSFPicture signaturePicture = patriarch.CreatePicture(anchor, index);

here's something you can try:

You see that property, anchor.AnchorType = 2;? try setting that to 0 or 3 and see what it does. In the C# (NPOI) port, 0 will fit the image in just one cell with option 0.

Here's some example code (used in a C# Asp.net project, just in case someone wanders here that needs it):

HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet1 = hssfworkbook.CreateSheet(sheetName);
//map the path to the img folder
string imagesPath = System.IO.Path.Combine(Server.MapPath("~"), "img");
//grab the image file
imagesPath = System.IO.Path.Combine(imagesPath, "image.png");
//create an image from the path
System.Drawing.Image image = System.Drawing.Image.FromFile(imagesPath);
MemoryStream ms = new MemoryStream();
//pull the memory stream from the image (I need this for the byte array later)
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//the drawing patriarch will hold the anchor and the master information
HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();
//store the coordinates of which cell and where in the cell the image goes
HSSFClientAnchor anchor = new HSSFClientAnchor(20, 0, 40, 20, 3, 10, 4, 11);
//types are 0, 2, and 3. 0 resizes within the cell, 2 doesn't
anchor.AnchorType = 2;
//add the byte array and encode it for the excel file
int index = hssfworkbook.AddPicture(ms.ToArray(), HSSFPicture.PICTURE_TYPE_PNG);
HSSFPicture signaturePicture = patriarch.CreatePicture(anchor, index);
为你拒绝所有暧昧 2024-11-09 06:20:17

可以通过三个步骤实现。
首先,你应该插入图片
二、在文件中添加ClientAnchor,将图片定位到某些单元格
第三,使用棘手的方式调整图片大小,否则很难在单元格内制作图片

It's possible by three steps.
First, you should insert the picture
Second, add the ClientAnchor to the file to locate the picture to some cells
Third, resize the picture using tricky way otherwise it's hard to make a picture inside a cell

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文