c# NPOI 如何在指定單元格導(dǎo)入導(dǎo)出圖片
Intro
我維護(hù)了一個(gè) NPOI 的擴(kuò)展(WeihanLi.Npoi),主要用來導(dǎo)入導(dǎo)出 Excel 數(shù)據(jù),最近有網(wǎng)友提出了導(dǎo)入 Excel 的時(shí)候解析圖片的需求,于是就有了本文的探索
導(dǎo)入Excel 時(shí)解析圖片
xls 和 xlsx 的 API 稍有不同,詳細(xì)可以直接參考以下代碼,實(shí)現(xiàn)代碼如下:
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 是一個(gè)自定義的結(jié)構(gòu)體,表示當(dāng)前單元格的位置,源碼如下:
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();
}
根據(jù)上面的代碼,我們就可以獲取到獲取到所有的圖片以及圖片的所在位置,這樣根據(jù)單元格位置去找圖片信息的時(shí)候就會(huì)很方便了
導(dǎo)出 Excel 時(shí)設(shè)置圖片
實(shí)現(xiàn)代碼如下:
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;
}
通過上面的代碼我們就可以在指定的單元格設(shè)置圖片,目前沒有支持單元格合并操作,有需要自己進(jìn)行修改
WeihanLi.Npoi
WeihanLi.Npoi 在 1.15.0 版本中增加了圖片導(dǎo)入導(dǎo)出的支持,使用示例可以參考下面的單元測試:
[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!;
}
導(dǎo)入時(shí)會(huì)自動(dòng)將 byte[] 類型的屬性嘗試獲取對(duì)應(yīng)的單元格位置的圖片,如果在對(duì)應(yīng)的位置找到了圖片就能夠讀取到圖片的字節(jié)數(shù)組信息映射到 model 里的字節(jié)數(shù)組屬性
除此之外,還支持直接導(dǎo)入的時(shí)候?qū)D片信息 Map 到 IPictureData 屬性上,但是覺得還是字節(jié)數(shù)組更通用一些,如果對(duì)此感興趣可以參考項(xiàng)目源碼以及單元測試
More
感謝 @ZeguangZhang94 童鞋提出的需求和幫忙測試~
如果你也有類似的讀取指定單元格的圖片或者在指定單元格插入圖片的需求,可以試一下上面的方法,希望對(duì)你有幫助,可以直接引用我的類庫或者直接拷貝源碼到自己的項(xiàng)目里使用
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
- https://github.com/WeihanLi/WeihanLi.Npoi/issues/99
以上就是c# NPOI 如何在指定單元格導(dǎo)入導(dǎo)出圖片的詳細(xì)內(nèi)容,更多關(guān)于NPOI 在指定單元格導(dǎo)入導(dǎo)出圖片的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
c#?Task.Wait()與awaiat?Task異常處理的區(qū)別說明
這篇文章主要介紹了c#?Task.Wait()與awaiat?Task異常處理的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
C# IQueryable<T>揭開表達(dá)式樹的神秘面紗
這篇文章主要介紹了C# IQueryable<T>表達(dá)式樹,對(duì)IQueryable<T>感興趣的同學(xué),必須要仔細(xì)看一下2021-04-04
關(guān)于Unity中RectTransform與transform的區(qū)別
這篇文章主要介紹了Unity中RectTransform與transform的區(qū)別,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01
c#判斷字符是否為中文的三種方法分享(正則表達(dá)式判斷)
判斷一個(gè)字符是不是漢字通常有三種方法,第一種用 ASCII 碼判斷,第二種用漢字的UNICODE編碼范圍判斷,第三種用正則表達(dá)式判斷,以下是具體方法2014-01-01
C#過濾DataTable中空數(shù)據(jù)和重復(fù)數(shù)據(jù)的示例代碼
這篇文章主要給大家介紹了關(guān)于C#過濾DataTable中空數(shù)據(jù)和重復(fù)數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
詳解C#實(shí)現(xiàn)在Excel單元格中應(yīng)用多種字體格式
在Excel中,可對(duì)單元格中的字符串設(shè)置多種不同樣式。本文,將以C#及VB.NET代碼為例,介紹如何在Excel同一個(gè)單元格中應(yīng)用多種字體樣式,感興趣的可以了解一下2022-05-05

