C# NPOI,怎么实现EXCEL多行,带有合并单元格,且有图片的复制,插入到指定行?
需要保留原多行的格式,内容
C# NPOI,怎么实现EXCEL多行,带有合并单元格,且有图片的复制,插入到指定行?
需要保留原多行的格式,内容
可以使用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();
}
}
}