当前位置: 首页 > news >正文

.NET Core NPOI 导出图片到Excel指定单元格并自适应宽度

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 

参考文章:【小5聊】C# NPOI添加图片到Excel指定单元格并自适应宽度_npoi excle 插入图片-CSDN博客 

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

http://www.lryc.cn/news/520322.html

相关文章:

  • python bs4 selenium 查找a href=javascript:();的实际点击事件和url
  • 三 BH1750 光感驱动调试1
  • UE材质节点Fresnel
  • linux的大内核锁与顺序锁
  • 用户注册模块用户校验(头条项目-05)
  • 面向对象的基本概念
  • 深度学习每周学习总结R4(LSTM-实现糖尿病探索与预测)
  • 如何使用 PHP 操作亚马逊 S3 对象云存储
  • 26_Redis RDB持久化
  • 标准Android开发jdk和gradle和gradle AGP和AndroidStudio对应版本
  • 太速科技-628-基于VU3P的双路100G光纤加速计算卡
  • 潜力巨大但道路曲折的量子计算
  • LabVIEW驱动电机实现样品自动搜索
  • React Native Hooks开发指南
  • 腾讯云AI代码助手编程挑战赛-厨房助手之AI大厨
  • ubuntu22.04 gcc,g++从10.5切换到低版本9.5
  • 在 WSL 中使用 Jupyter Notebook 的 TensorBoard 启动问题与解决方法
  • Spring Boot 2 学习全攻略
  • 海豚调度DolphinScheduler-3.1.9配置windows本地开发环境
  • 【机器学习:十九、反向传播】
  • 线形回归与小批量梯度下降实例
  • SpringCloud微服务:基于Nacos组件,整合Dubbo框架
  • Golang 简要概述
  • web前端第三次作业---制作可提交的用户注册表
  • 教育邮箱的魔力:免费获取Adobe和JetBrains软件
  • sympy常用函数与错误笔记
  • 47_Lua文件IO操作
  • nginx-lua模块处理流程
  • 【大数据】机器学习-----最开始的引路
  • 【前端】自学基础算法 -- 21.图的广度优先搜索