.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中的图片,将其转换成字节流存到集合中,方便后续对其进行操作。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。
原文地址:https://blog.csdn.net/hefeng_aspnet/article/details/144698158
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!