使用NPOI core插入图片
阅读原文时间:2023年07月09日阅读:1

闲的无聊,封装一个NPOI core插入图片,下面贴上代码,有注释,我就不讲解了

public class ExcelHelper  
{  
    /// <summary>  
    /// excel插入图片  
    /// </summary>  
    /// <param name="excelPath">excel路径</param>  
    /// <param name="imgStream">图片流</param>  
    /// <param name="rowNumber">图片插入到哪行</param>  
    /// <param name="pictureType">图片类型</param>  
    /// <param name="cellNumber">图片插入到那列</param>  
    /// <param name="height">图片所在的那行的高度</param>  
    /// <param name="sheelNumber">哪个sheel,默认为第一个</param>  
    public static void InsertImage(string excelPath, Stream imgStream, PictureType pictureType, int rowNumber, int cellNumber, short height, int sheelNumber = 0)  
    {  
        if (!File.Exists(excelPath))  
        {  
            throw new Exception($"file path:'{excelPath}' does not exists.");  
        }  
        using (Stream excelStream = new FileStream(excelPath, FileMode.Open))  
        {  
            IWorkbook workbook = WorkbookFactory.Create(excelStream);  
            ///判断sheet是否存在  
            ISheet sheet = workbook.GetSheetAt(sheelNumber);  
            if (sheet == null)  
            {  
                sheet = workbook.CreateSheet($"sheet{sheelNumber}");  
            }  
            ///判断行是否存在  
            IRow row = sheet.GetRow(rowNumber);  
            if (row == null)  
            {  
                row = sheet.CreateRow(rowNumber);  
            }  
            //设置行高  
            row.Height = height;  
            ///判断列是否存在  
            ICell cell = row.GetCell(cellNumber);  
            if (cell == null)  
            {  
                cell = row.CreateCell(cellNumber);  
            }  
            //将图片流读取到byte数组  
            byte\[\] bytes = new byte\[imgStream.Length\];  
            imgStream.Read(bytes, 0, (int)imgStream.Length);

            int pictureIdx = workbook.AddPicture(bytes, pictureType);  
            IDrawing patriarch = sheet.CreateDrawingPatriarch();  
            //指定图片插入的位置  
            IClientAnchor anchor = new XSSFClientAnchor(0, 10, 0, 0, cellNumber, rowNumber, cellNumber + 1, rowNumber + 1);  
            string extension = Path.GetExtension(excelPath);  
            if (extension == ".xls")  
            {  
                anchor = new HSSFClientAnchor(0, 10, 0, 0, cellNumber, rowNumber, cellNumber+1, rowNumber + 1);  
            }

            IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);

            using (Stream stream = File.OpenWrite(excelPath))  
            {  
                workbook.Write(stream);  
            }

        }  
    }  
}