ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

NPOI 在指定单元格导入导出图片

2021-03-04 21:00:36  阅读:180  来源: 互联网

标签:picture sheet int 单元格 NPOI 导入 var WeihanLi public


我维护了一个 NPOI 的扩展(WeihanLi.Npoi),主要用来导入导出 Excel 数据,最近有网友提出了导入 Excel 的时候解析图片的需求,于是就有了本文的探索

导入Excel 时解析图片#
xls 和 xlsx 的 API 稍有不同,详细可以直接参c#教程考以下代码,实现代码如下:

public static Dictionary<CellPosition, IPictureData> GetPicturesAndPosition(this ISheet sheet)
{
    var dictionary = new Dictionary<CellPosition, IPictureData>();
    if (sheet.Workbook is HSSFWorkbook)
    {
        foreach (var shape in ((HSSFPatriarch)sheet.DrawingPatriarch).Children)
        {
            if (shape is HSSFPicture picture)
            {
                var position = new CellPosition(picture.ClientAnchor.Row1, picture.ClientAnchor.Col1);
                dictionary[position] = picture.PictureData;
            }
        }
    }
    else if (sheet.Workbook is XSSFWorkbook)
    {
        foreach (var shape in ((XSSFDrawing)sheet.DrawingPatriarch).GetShapes())
        {
            if (shape is XSSFPicture picture)
            {
                var position = new CellPosition(picture.ClientAnchor.Row1, picture.ClientAnchor.Col1);
                dictionary[position] = picture.PictureData;
            }
        }
    }
    return dictionary;
}

CellPosition 是一个自定义的结构体,表示当前单元python基础教程格的位置,源码如下:



public readonly struct CellPosition : IEquatable<CellPosition>
{
    public CellPosition(int row, int col)
    {
        Row = row;
        Column = col;
    }

    public int Row { get; }
    public int Column { get; }

    public bool Equals(CellPosition other)
    {
        return Row == other.Row && Column == other.Column;
    }

    public override bool Equals(object? obj) => obj is CellPosition other && Equals(other);

    public override int GetHashCode() => $"{Row}_{Column}".GetHashCode();
}

根据上面的代码,我们就可以获取到获取到所有的图片以及图片的所在位置,这样根据单元格位置去找图片信息的时候就会很方便了

导出 Excel 时设置图片#
实现代码如下:

public static bool TryAddPicture(this ISheet sheet, int row, int col, byte[] pictureBytes, PictureType pictureType = PictureType.PNG)
{
    if (sheet is null)
    {
        throw new ArgumentNullException(nameof(sheet));
    }

    try
    {
        var pictureIndex = sheet.Workbook.AddPicture(pictureBytes, pictureType);

        var clientAnchor = sheet.Workbook.GetCreationHelper().CreateClientAnchor();
        clientAnchor.Row1 = row;
        clientAnchor.Col1 = col;

        var picture = (sheet.DrawingPatriarch ?? sheet.CreateDrawingPatriarch())
            .CreatePicture(clientAnchor, pictureIndex);
        picture.Resize();
        return true;
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
    }

    return false;
}
通过上面的代码我们就可以在指定的单元格设置图片,目前没有支持单元格合并操作,有需要自己进行修改

WeihanLi.Npoi#
WeihanLi.Npoi 在 1.15.0 版本中增加了图片导入导出的支持,使用示例可以参考下面的单元测试:

[Theory]
[ExcelFormatData]
public async Task ImageImportExportTest(ExcelFormat excelFormat)
{
    using var httpClient = new HttpClient();
    var imageBytes = await httpClient.GetByteArrayAsync("https://weihanli.xyz/assets/avator.jpg");
    var list = Enumerable.Range(1, 5)
        .Select(x => new ImageTest() { Id = x, Image = imageBytes })
        .ToList();
    var excelBytes = list.ToExcelBytes(excelFormat);
    var importResult = ExcelHelper.ToEntityList<ImageTest>(excelBytes, excelFormat);
    Assert.NotNull(importResult);
    Assert.Equal(list.Count, importResult.Count);
    for (var i = 0; i < list.Count; i++)
    {
        Assert.NotNull(importResult[i]);
        var result = importResult[i]!;
        Assert.Equal(list[i].Id, result.Id);
        Assert.NotNull(result.Image);
        Assert.True(list[i].Image.SequenceEqual(result.Image));
    }
}

private class ImageTest
{
    public int Id { get; set; }

    public byte[] Image { get; set; } = null!;
}

导入时会自动将 byte[] 类型的属性尝试获取对应的单元格位置的图片,如果在对应的位置找到了图片就能够读取到图片的字节数组信息映射到 model 里的字节数组属性

除此之外,还支持直接导入的时候将图片信息 Map 到 IPictureData 属性上,但是觉得还是字节数组更通用一些,如果对此感兴趣可以参考项目源码以及单元测试

More#
感谢 @ZeguangZhang94 童鞋提出的需求和帮忙测试~

如果你也有类似的读取指定单元格的图片或者在指定单元格插入图片的需求,可以试一下上面的方法,希望对你有帮助,可以直接引用我的类库或者直接拷贝源码到自己的项目里使用

References#
https://github.com/WeihanLi/WeihanLi.Npoi
https://github.com/WeihanLi/WeihanLi.Npoi/blob/dev/src/WeihanLi.Npoi/NpoiExtensions.cs#L1143
https://stackoverflow.com/questions/24084129/read-image-from-excel-file-using-npoi
https://stackoverflow.com/questions/41138848/add-image-to-excel-xlsx-using-npoi-c-sharp
https://github.com/WeihanLi/WeihanLi.Npoi/issues/99

作者:WeihanLi

出处:https://www.cnblogs.com/weihanli/p/14471773.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

标签:picture,sheet,int,单元格,NPOI,导入,var,WeihanLi,public
来源: https://blog.csdn.net/chinaherolts2008/article/details/114377606

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有