.NET使用NPOI实现读取带有图片的excel数据

来自:网络
时间:2024-06-09
阅读:

前言

在.net使用npoi插件进行批量导入时,获取excel中的图片数据,存到集合中。

使用步骤

1.定义类PictureData

代码如下:

public class PictureData
{
    public byte[] Data { get; set; }
}

2.数据集引用

using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel.Extensions;

npoi插件需要自己下载。

3.定义获取excel图片数据的方法GetDTWithImg

    /// <summary>
    /// 获取excel中图片数据
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <returns>list</returns>
 private List<PictureData> GetDTWithImg(string path)
    {
        using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            IWorkbook workbook = null;
            ISheet sheet = null;

            workbook = WorkbookFactory.Create(file);
            sheet = workbook.GetSheet("Sheet1");
            if (sheet == null)
            {
                sheet = workbook.GetSheetAt(0);
            }

            // 获取绘图对象
            XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();
            List<XSSFPicture> picturesInColumnA = new List<XSSFPicture>();
            List<XSSFShape> shapes = drawing.GetShapes();
            foreach (XSSFShape shape in shapes)
            {
                if (shape is XSSFPicture)
                {
                    XSSFPicture picture = (XSSFPicture)shape;
                    XSSFClientAnchor anchor = (XSSFClientAnchor)picture.GetPreferredSize();                  
                    picturesInColumnA.Add(picture);
                }
            }
            List<PictureData> pictureDataList = new List<PictureData>();
            //将图片数据放到集合中
            foreach (XSSFPicture picture in picturesInColumnA)
            {
                byte[] pictureData = picture.PictureData.Data;
                PictureData data = new PictureData
                {                   
                    Data = pictureData
                };
                pictureDataList.Add(data);
            }
            return pictureDataList;
        }

    }

总结

通过该方法可以获取excel中的图片,将其转换成字节流存到集合中,方便后续对其进行操作。

返回顶部
顶部