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

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;
}
                                if (dic.TryGetValue(posion, out var pictureData))
                                {
                                    var pic = "jpg";
                                    switch (pictureData.PictureType)
                                    {
                                        case PictureType.PNG: { pic = "png"; } break;
                                        case PictureType.JPEG: { pic = "jpg"; } break;
                                    }
                                    var saveName = $"{huohao}.{pic}";
                                    var filepath = Path.Combine(fileSaveFloder, saveName);
                                    if (File.Exists(filepath))
                                    {
                                        File.Delete(filepath);
                                    }
                                    File.WriteAllBytes(Path.Combine(fileSaveFloder, saveName), pictureData.Data);
                                  
                                }
    /// <summary>
    /// CellPosition 是一个自定义的结构体,表示当前单元格的位置
    /// </summary>
    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();
    }

posted @ 2021-09-23 10:39  蓝创精英团队  阅读(4)  评论(0)    收藏  举报  来源