WeihanLi / WeihanLi.Npoi

NPOI Extensions, excel/csv importer/exporter for IEnumerable<T>/DataTable, fluentapi(great flexibility)/attribute configuration
https://weihanli.github.io/WeihanLi.Npoi/index.html
Apache License 2.0
203 stars 53 forks source link

ExcelHelper.ToEntityList<T> ,对象属性包含图片映射时,导入表格无图直接报错 #111

Closed lianghao620 closed 3 years ago

lianghao620 commented 3 years ago

ExcelHelper.ToEntityList

lianghao620 commented 3 years ago

ExcelHelper.ToEntityList

当对象属性配置了 [Column("图片")] public byte[] Image { get; set; }

导入的excel无图时直接报错 。 我认为应该兼容无图的情况 。

    /// <summary>
    /// get pictures with position in current sheet
    /// </summary>
    /// <param name="sheet">sheet</param>
    /// <returns></returns>
    public static Dictionary<CellPosition, IPictureData> GetPicturesAndPosition(this ISheet sheet)
    {
        if (sheet is null)
        {
            throw new ArgumentNullException(nameof(sheet));
        }
        var dictionary = new Dictionary<CellPosition, IPictureData>();
        **if(sheet.DrawingPatriarch == null) return dictionary;**//防止 无图报错
        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;
    }
WeihanLi commented 3 years ago

感谢反馈和修改建议,如果有时间的话欢迎 PR,晚上回去之后发布一个新版本修复一下

WeihanLi commented 3 years ago

发布了一个新版本 1.17.0,可以试一下 https://www.nuget.org/packages/WeihanLi.Npoi/1.17.0