轉載C# NPOI添加圖片到Excel指定單元格並自適應寬度
框架:.net core 2.1
NPOI:支持xlsx,.xls,版本=2.5.3
XLS:HSSFWorkbook,主要前綴HSS,
XLSX:XSSFWorkbook,主要前綴XSS,using NPOI.XSSF.UserModel;
1、導出Excel添加圖片效果,以及可自適應(以下有調整過寬度)
2、Nuget安裝NPOI
直接安裝最新版本 - 2.5.3
3、最新版本數據類型大小寫有改動
之前版本是全部大小,現在的是首字母大寫
region 程序集 NPOI, Version=2.5.3.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1
// C:\Users\DELL.nuget\packages\npoi\2.5.3\lib\netstandard2.0\NPOI.dll
endregion
namespace NPOI.SS.UserModel
{
public enum CellType
{
Unknown = -1,
Numeric = 0,
String = 1,
Formula = 2,
Blank = 3,
Boolean = 4,
Error = 5
}
}
4、JSON數據
[{
"id": 1,
"productNum": 10,
"addTime": "2021-07-15T08:59:49.997",
"updateTime": "0001-01-01T00:00:00",
"productCover": "AmazonProduct/20210715/bc21aee9-b35b-49e6-a50c-7d95178ff487.jpg",
"productName": "DEERC DE22 GPS Drone with 4K Camera 2-axis Gimbal, EIS Anti-Shake, 5G FPV Live Video Brushless Motor, Auto Return Home, Selfie, Follow Me, Waypoints, Circle Fly 52Min Flight with Carrycase",
"productPrice": 123.00
}, {
"id": 2,
"productNum": 66,
"addTime": "2021-07-15T08:58:59.257",
"updateTime": "0001-01-01T00:00:00",
"productCover": "AmazonProduct/20210715/cea4ff1b-6d5f-46fa-9bea-3745cd80a7d5.jpg",
"productName": "Neleus Men's Lightweight Workout Running Athletic Shorts with Pockets",
"productPrice": 26.89
}]
5、導出xls格式代碼
region version=2021.07.15 導出 - Excel - xls - 例子
[HttpPost]
public IActionResult ExcelXls(Model_Request requestModel)
{
try
{
HSSFWorkbook workbook = new HSSFWorkbook(); //創建一個工作簿
ISheet sheet = workbook.CreateSheet("labelName"); //創建一個sheet
//設置excel列寬,像素是1/256
sheet.SetColumnWidth(0, 18 * 256);
sheet.SetColumnWidth(1, 18 * 256);
IRow rowTitle = sheet.CreateRow(0);//創建表頭行
rowTitle.CreateCell(0, CellType.String).SetCellValue("編號");
rowTitle.CreateCell(1, CellType.String).SetCellValue("產品封面");
rowTitle.CreateCell(2, CellType.String).SetCellValue("產品名稱");
rowTitle.CreateCell(3, CellType.String).SetCellValue("產品價格");
rowTitle.CreateCell(4, CellType.String).SetCellValue("產品狀態");
rowTitle.CreateCell(5, CellType.String).SetCellValue("產品數量");
rowTitle.CreateCell(6, CellType.String).SetCellValue("添加時間");
List<Model_Response> list = new List<Model_Response>();
list = new Data().List(requestModel);
if (list.Count > 0)
{
int rowline = 1; //從第二行開始(索引從0開始)
foreach (AmazonProductApplyModel_Response item in list)
{
IRow row = sheet.CreateRow(rowline);
row.Height = 80 * 20; //設置excel行高,像素點是1/20
row.CreateCell(0, CellType.String).SetCellValue(item.id); //編號
//===產品封面===
//將圖片文件讀入一個字符串
byte[] bytes = System.IO.File.ReadAllBytes(PathHelper.BaseDirectory() + item.productCover); //路徑(加載圖片完整路徑)
int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
//把圖片添加到相應的位置
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(70, 10, 0, 0, 1, rowline, 2, rowline + 1);
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
//===/產品封面===
row.CreateCell(2, CellType.String).SetCellValue(item.productName); //產品名稱
row.CreateCell(3, CellType.String).SetCellValue(item.productPrice.ToString()); //產品價格
row.CreateCell(4, CellType.String).SetCellValue(item.productStatus); //產品狀態
row.CreateCell(5, CellType.String).SetCellValue(item.productNum.ToString()); //補貨數量
row.CreateCell(6, CellType.String).SetCellValue(item.addTime.ToString()); //添加時間
rowline++;
}
//設置自適應寬度
for (int columnNum = 0; columnNum < 7; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow = sheet.GetRow(rowNum);
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}
}
//保存文件
string name = Guid.NewGuid().ToString() + ".xls";
string path = AppDomain.CurrentDomain.BaseDirectory + "\\" + name;
using (Stream stream = System.IO.File.Create(path))
{
workbook.Write(stream);
}
return Json(new { c = 200, m = "導出成功", path = path });
}
catch (Exception ex)
{
}
finally
{
}
return Json(new { c = 200, m = "導出成功", path = path });
}
#endregion
6、導出xlsx格式代碼
#region version=2021.07.15 導出 - Excel - xls - 例子
[HttpPost]
public IActionResult ExcelXls(Model_Request requestModel)
{
try
{
XSSFWorkbook workbook = new XSSFWorkbook(); //創建一個工作簿
ISheet sheet = workbook.CreateSheet("labelName"); //創建一個sheet
//設置excel列寬,像素是1/256
sheet.SetColumnWidth(0, 18 * 256);
sheet.SetColumnWidth(1, 18 * 256);
IRow rowTitle = sheet.CreateRow(0);//創建表頭行
rowTitle.CreateCell(0, CellType.String).SetCellValue("編號");
rowTitle.CreateCell(1, CellType.String).SetCellValue("產品封面");
rowTitle.CreateCell(2, CellType.String).SetCellValue("產品名稱");
rowTitle.CreateCell(3, CellType.String).SetCellValue("產品價格");
rowTitle.CreateCell(4, CellType.String).SetCellValue("產品狀態");
rowTitle.CreateCell(5, CellType.String).SetCellValue("產品數量");
rowTitle.CreateCell(6, CellType.String).SetCellValue("添加時間");
List<Model_Response> list = new List<Model_Response>();
list = new Data().List(requestModel);
if (list.Count > 0)
{
int rowline = 1; //從第二行開始(索引從0開始)
foreach (AmazonProductApplyModel_Response item in list)
{
IRow row = sheet.CreateRow(rowline);
row.Height = 80 * 20; //設置excel行高,像素點是1/20
row.CreateCell(0, CellType.String).SetCellValue(item.id); //編號
//===產品封面===
//將圖片文件讀入一個字符串
byte[] bytes = System.IO.File.ReadAllBytes(PathHelper.BaseDirectory() + item.productCover); //路徑(加載圖片完整路徑)
int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
//把圖片添加到相應的位置
XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch();
XSSFClientAnchor anchor = new XSSFClientAnchor(70, 10, 0, 0, 1, rowline, 2, rowline + 1);
XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
//===/產品封面===
row.CreateCell(2, CellType.String).SetCellValue(item.productName); //產品名稱
row.CreateCell(3, CellType.String).SetCellValue(item.productPrice.ToString()); //產品價格
row.CreateCell(4, CellType.String).SetCellValue(item.productStatus); //產品狀態
row.CreateCell(5, CellType.String).SetCellValue(item.productNum.ToString()); //補貨數量
row.CreateCell(6, CellType.String).SetCellValue(item.addTime.ToString()); //添加時間
rowline++;
}
//設置自適應寬度
for (int columnNum = 0; columnNum < 7; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow = sheet.GetRow(rowNum);
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}
}
//保存文件
string name = Guid.NewGuid().ToString() + ".xls";
string path = AppDomain.CurrentDomain.BaseDirectory + "\\" + name;
using (Stream stream = System.IO.File.Create(path))
{
workbook.Write(stream);
}
return Json(new { c = 200, m = "導出成功", path = path });
}
catch (Exception ex)
{
}
finally
{
}
return Json(new { c = 200, m = "導出成功", path = path });
}
#endregion
————————————————
版權聲明:本文為CSDN博主「小5聊」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/lmy_520/article/details/118752517