Adding images into Excel using EPPlus

I am trying to add the same image multiple times into an excel file using EPPlus. I am using the following code to do so:

Image logo = Image.FromFile(path);
ExcelPackage package = new ExcelPackage(info);
var ws = package.Workbook.Worksheets.Add("Test Page");
for(int a = 0; a < 5; a++)
{
    ws.Row(a*5).Height = 39.00D;
    var picture = ws.Drawings.AddPicture(a.ToString(), logo);
    picture.SetPosition(a*5, 0, 2, 0);
}

Everything works perfectly and all the images are correctly added but they are stretched downwards. Here is what one of the pictures should look like:

But it looks like this in excel:

在这里输入图像描述

I have to resize each row of the start of each picture but I dont think that would be affecting it. Would there be a way to add the pictures/do what I am trying to do or would I have to copy-paste the images in manually? (I am using the picture as an example)

Thanks.


I'm not sure if this is the best solution but definetly a workaround for your problem.

Here's what I did:

ExcelPackage package = new ExcelPackage();
var ws = package.Workbook.Worksheets.Add("Test Page");

for (int a = 0; a < 5; a++)
{
    ws.Row(a * 5).Height = 39.00D;
}

for (int a = 0; a < 5; a++)
{
    var picture = ws.Drawings.AddPicture(a.ToString(), logo);
    picture.SetPosition(a * 5, 0, 2, 0);
}

Here is how it looks.

在这里输入图像描述

For some reason when we have the row height set, its interfering with the picture height.


这是您可以在C#中应用的一种解决方案。

private void AddImage(ExcelWorksheet oSheet, int rowIndex, int colIndex, string imagePath)
{
    Bitmap image = new Bitmap(imagePath);
    ExcelPicture excelImage = null;
    if (image != null)
    {
        excelImage = oSheet.Drawings.AddPicture("Debopam Pal", image);
        excelImage.From.Column = colIndex;
        excelImage.From.Row = rowIndex;
        excelImage.SetSize(100, 100);
        // 2x2 px space for better alignment
        excelImage.From.ColumnOff = Pixel2MTU(2);
        excelImage.From.RowOff = Pixel2MTU(2);
    }
}

public int Pixel2MTU(int pixels)
{
    int mtus = pixels * 9525;
    return mtus;
}

try this

Image logo = Image.FromFile(path);
ExcelPackage package = new ExcelPackage(info);
var ws = package.Workbook.Worksheets.Add("Test Page");
for(int a = 0; a < 5; a++)
{
    ws.Row(a*5).Height = 39.00D;
    var picture = ws.Drawings.AddPicture(a.ToString(), logo);
    // xlMove disables the auto resizing
    picture.Placement = xlMove; //XLPlacement : xlMoveAndSize,xlMove,xlFreeFloating
    picture.SetPosition(a*5, 0, 2, 0);
}

or

Image logo = Image.FromFile(path);
ExcelPackage package = new ExcelPackage(info);
var ws = package.Workbook.Worksheets.Add("Test Page");
for(int a = 0; a < 5; a++)
{
    ws.Row(a*5).Height = 39.00D;
    var picture = ws.Drawings.AddPicture(a.ToString(), logo);
    picture.From.Column = 0;
    picture.From.Row = a;
    picture.SetSize(120, 150);
}
链接地址: http://www.djcxy.com/p/72020.html

上一篇: 使用EPPlus合并单元格?

下一篇: 使用EPPlus将图像添加到Excel中