NPOI 在指定单元格导入导出图片
NPOI 在指定单元格导入导出图片
Intro
我维护了一个 NPOI 的扩展,主要用来导入导出 Excel 数据,最近有网友提出了导入 Excel 的时候解析图片的需求,于是就有了本文的探索
导入Excel 时解析图片
xls 和 xlsx 的 API 稍有不同,详细可以直接参考以下代码,实现代码如下:
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;
}
CellPosition 是一个自定义的结构体,表示当前单元格的位置,源码如下:
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();
}
根据上面的代码,我们就可以获取到获取到所有的图片以及图片的所在位置,这样根据单元格位置去找图片信息的时候就会很方便了
导出 Excel 时设置图片
实现代码如下:
public static bool TryAddPicture(this ISheet sheet, int row, int col, byte[] pictureBytes, PictureType pictureType = PictureType.PNG)
{
if (sheet is null)
{
throw new ArgumentNullException(nameof(sheet));
}
try
{
var pictureIndex = sheet.Workbook.AddPicture(pictureBytes, pictureType);
var clientAnchor = sheet.Workbook.GetCreationHelper().CreateClientAnchor();
clientAnchor.Row1 = row;
clientAnchor.Col1 = col;
var picture = (sheet.DrawingPatriarch ?? sheet.CreateDrawingPatriarch())
.CreatePicture(clientAnchor, pictureIndex);
picture.Resize();
return true;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
return false;
}
通过上面的代码我们就可以在指定的单元格设置图片,目前没有支持单元格合并操作,有需要自己进行修改
WeihanLi.Npoi
WeihanLi.Npoi 在 1.15.0 版本中增加了图片导入导出的支持,使用示例可以参考下面的单元测试:
[Theory]
[ExcelFormatData]
public async Task ImageImportExportTest(ExcelFormat excelFormat)
{
using var httpClient = new HttpClient();
var imageBytes = await httpClient.GetByteArrayAsync("https://weihanli.xyz/assets/avator.jpg");
var list = Enumerable.Range(1, 5)
.Select(x => new ImageTest() { Id = x, Image = imageBytes })
.ToList();
var excelBytes = list.ToExcelBytes(excelFormat);
var importResult = ExcelHelper.ToEntityList<ImageTest>(excelBytes, excelFormat);
Assert.NotNull(importResult);
Assert.Equal(list.Count, importResult.Count);
for (var i = 0; i < list.Count; i++)
{
Assert.NotNull(importResult[i]);
var result = importResult[i]!;
Assert.Equal(list[i].Id, result.Id);
Assert.NotNull(result.Image);
Assert.True(list[i].Image.SequenceEqual(result.Image));
}
}
private class ImageTest
{
public int Id { get; set; }
public byte[] Image { get; set; } = null!;
}
导入时会自动将 byte[] 类型的属性尝试获取对应的单元格位置的图片,如果在对应的位置找到了图片就能够读取到图片的字节数组信息映射到 model 里的字节数组属性
More
感谢 @ZeguangZhang94 童鞋提出的需求和帮忙测试~
如果你也有类似的读取指定单元格的图片或者在指定单元格插入图片的需求,可以试一下上面的方法,希望对你有帮助
References
- https://github.com/WeihanLi/WeihanLi.Npoi
- https://github.com/WeihanLi/WeihanLi.Npoi/blob/dev/src/WeihanLi.Npoi/NpoiExtensions.cs#L1143
- https://stackoverflow.com/questions/24084129/read-image-from-excel-file-using-npoi
- https://stackoverflow.com/questions/41138848/add-image-to-excel-xlsx-using-npoi-c-sharp
NPOI 在指定单元格导入导出图片的更多相关文章
- c#在Excel指定单元格中插入图片
方法一: /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度./// 注意:图片必须是绝对物理路径/// </summary>/// <param name="R ...
- NPOI 修改指定单元格字体颜色
//创建一个字体颜色 IFont font = hssfworkbook.CreateFont(); //红色 font.Color = HSSFColor.Red.Index; //样式 ICell ...
- NPOI扩展--判断指定单元格是否为合并单元格和输出该单元格的行列跨度(维度)
因工作需要用到跨合并单元格获取数据,所以写了个NPOI扩展类. 主要方法如下: 1.判断指定行/列索引(单元格)是否为合并单元格. 2.获取指定列索引的实际含有数据的单元格. 3.返回指定行/列索引的 ...
- 27.openpyxl 向指定单元格添加图片并修改图片大小 以及修改单元格行高列宽
openpyxl 向指定单元格添加图片并修改图片大小 以及修改单元格行高列宽 from openpyxl import Workbook,load_workbook from openpyxl.dra ...
- dev gridview指定单元格cell获取坐标
DevExpress.XtraGrid.Views.Grid.ViewInfo.GridViewInfo Info2 = gvQueryResult.GetViewInfo() as DevExpre ...
- 使用VBA将Excel指定单元格数据、字符串或者图表对象插入到Word模板指定书签处
准备工作: 1.首先需要提供一个word模板,并且标记好您要插入书签的位置,定义书签的命名.如图 2.模拟您要插入的Excel原始数据和图表对象 插入代码如下: Private Sub Command ...
- python接口自动化测试--数据分离读取Excal指定单元格数据
上一篇博客讲了怎么批量读取Excal单元格数据,现在咱们说一下怎么读取Excal指定单元格数据. 一.首先建一个Test_Main类 #!/usr/bin/python # -*- coding: U ...
- VBA赋值给指定单元格
这是一个Range对象基本操作实例,对指定单元格赋值,然后使用弹窗获取值. 代码如下: Sub test1() Worksheets( MsgBox "工作表Sheet1内单元格A5中的值为 ...
- DataGridView单元格显示GIF图片
本文转载:http://home.cnblogs.com/group/topic/40730.html DataGridView单元格显示GIF图片 gifanimationindatagrid.ra ...
随机推荐
- ACDream手速赛2
地址:http://acdream.info/onecontest/1014 都是来自Codeforce上简单题. A. Boy or Girl 简单字符串处理 B. Walking in ...
- 阅读笔记:Item-based Collaborative Filtering Recommendation Algorithms
概要: 推荐系统通过信息获取技术解决在线的个人的消息.产品或者服务的推荐问题.这些系统,特别是基于k临近协同过滤算法,在网络上取得了广泛的成功.可用信息和访问人数的巨大增加成了推荐系统一个难题.基于商 ...
- 【noi 2.6_7624】山区建小学(DP)
题意:在m个村庄建n个小学,求所有村到最近小学的距离总的最小值. 解法:由于题目是求"离最近的学校",而不是前一个学校,所以枚举学校的具体位置不方便,可转化成区间(学校居区间中间) ...
- poj 3468A Simple Problem with Integers
Description You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. On ...
- 获取csc.exe路径
using System.Runtime.InteropServices; var frameworkPath = RuntimeEnvironment.GetRuntimeDirectory(); ...
- 国产网络损伤仪SandStorm -- 基本概念:什么是仿真引擎
"仿真引擎"在网络损伤仪SandStorm(www.minismb.com)或者网络IP仿真损伤仪中是一个最基本概念,它就相当于一个由两个物理以太网口组成的"网桥&quo ...
- [视频] FFMpeg 基本组成和入门示例
目录 FFmpeg基本组成 编解码工具 ffmpeg.exe ffmpeg.exe的工作流程 播放器 ffplay.exe 多媒体分析器 ffprobe FFmpeg基本组成 AVFormat 封装了 ...
- Redis-sentinel 哨兵(HA)
Sentinel 介绍 Redis-Sentinel 是 Redis 官方推荐的高可用性(HA)解决方案,当用 Redis 做 Master-slave 的高可用方案时,假如Master 宕机了,Re ...
- MySQL 多实例及其主从复制
目录 Mysql 实例 Mysql 多实例 创建多实例目录 编辑配置文件 初始化多实例数据目录 授权目录 启动多实例 连接多实例并验证 Mysql 多实例设置密码 设置密码后连接 Mysql 多实例主 ...
- hdu-6237
A Simple Stone Game Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Ot ...