.NetCore 使用 NPOI 读取带有图片的excel数据

在.NetCore使用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插件可以通过nuget安装或自己下载引用。

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中的图片,将其转换成字节流存到集合中,方便后续对其进行操作。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
weixin_4624462316 小时前
Python 使用 openpyxl 从 URL 读取 Excel 并获取 Sheet 及单元格样式信息
python·excel·openpyxl
wtsolutions17 小时前
MCP Server Integration - JSON to Excel for AI and Automation
json·excel
开开心心就好18 小时前
音频编辑工具,多端支持基础剪辑易操作
java·网络·windows·java-ee·电脑·maven·excel
vfvfb21 小时前
excel多个合并 xlsx工作表合并 多个excel合并到一张表
excel
金融小白数据分析之路1 天前
msoffcrypto-tool库 Excel 加密
python·excel
开开心心_Every1 天前
文件数量统计工具:支持多层文件夹数量统计
游戏·微信·pdf·excel·语音识别·swift·lisp
私人珍藏库1 天前
[吾爱大神原创工具] Excel 数据批量转 Word 工具(2026年最新版)
word·excel·工具·软件·win
linuxxx1101 天前
excel365批量拆分列并填充单元格
excel
徐赛俊1 天前
Excel 数据写入 PowerPoint 表格与文本框(涨跌幅颜色自动处理)
powerpoint·excel
好好学操作系统1 天前
notion+excel自动创建表格| 了解了notion api
数据库·python·oracle·excel·notion