guoheng90 2023-01-31 18:20 采纳率: 0%
浏览 65
已结题

C# NPOI,怎么实现EXCEL多行,带有合并单元格,且有图片的复制,插入到指定行?

C# NPOI,怎么实现EXCEL多行,带有合并单元格,且有图片的复制,插入到指定行?

需要保留原多行的格式,内容

  • 写回答

3条回答 默认 最新

  • heart_6662 2023-01-31 19:52
    关注

    可以使用NPOI的诸如IRow、ICell等对象来操作Excel的行和单元格。在插入多行,包含合并单元格和图片的内容时

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using System;
    using System.IO;
    
    namespace NPOIExample
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Step 1: Create a workbook and get the active worksheet
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("Sheet1");
    
                // Step 2: Create multiple rows
                IRow row1 = sheet.CreateRow(0);
                IRow row2 = sheet.CreateRow(1);
    
                // Step 3: Create cells in each row
                ICell cell11 = row1.CreateCell(0);
                ICell cell12 = row1.CreateCell(1);
                ICell cell21 = row2.CreateCell(0);
                ICell cell22 = row2.CreateCell(1);
            // Step 4: Fill in cell values
            cell11.SetCellValue("Row 1 Cell 1");
            cell12.SetCellValue("Row 1 Cell 2");
            cell21.SetCellValue("Row 2 Cell 1");
            cell22.SetCellValue("Row 2 Cell 2");
    
            // Step 5: Merge cells (for example, merge Row 1 Cell 1 and Row 1 Cell 2)
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 1));
    
            // Step 6: Add an image to a cell (for example, to Row 2 Cell 2)
            // Load the image into a memory stream
            var pictureData = File.ReadAllBytes("image.jpg");
            int pictureIndex = workbook.AddPicture(pictureData, PictureType.JPEG);
    
            // Create the drawing patriarch.  This is the top level container for all shapes. 
            var patriarch = sheet.CreateDrawingPatriarch();
    
            // Add a picture
            var anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 4);
            var picture = patriarch.CreatePicture(anchor, pictureIndex);
    
            // Step 7: Write the workbook to a file
            FileStream file = new FileStream("MultipleRowsWithMergedCellsAndPicture.xlsx", FileMode.Create);
            workbook.Write(file);
            file.Close();
        }
    }
    }
     
    
    
    
    
    评论

报告相同问题?

问题事件

  • 系统已结题 2月8日
  • 修改了问题 1月31日
  • 赞助了问题酬金15元 1月31日
  • 创建了问题 1月31日

悬赏问题

  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
  • ¥20 wpf datagrid单元闪烁效果失灵
  • ¥15 券商软件上市公司信息获取问题