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();
}
}
}
您可以使用NPOI组件来实现C#复制EXCEL带合并单元格和图片的多行。实现过程如下:
1.读取EXCEL模板文件,获取需要复制的多行,包括单元格合并信息,图片信息。
2.在EXCEL模板文件中创建新行,将多行内容复制到新行中。
3.将图片插入到新行对应的单元格中。
4.设置新行的单元格合并信息。
5.保存新的EXCEL文件。
下面是一个代码示例,该示例实现了从模板复制带有合并单元格和图片的多行,并将其插入到新的EXCEL文件中。
csharp
using System;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
namespace NPOI_Example
{
class Program
{
static void Main(string[] args)
{
IWorkbook workbook = null;
FileStream fs = null;
try
{
//读取模板文件
fs = new FileStream("template.xlsx", FileMode.Open, FileAccess.Read);
workbook = new XSSFWorkbook(fs);
ISheet sheet = workbook.GetSheetAt(0);
//获取需要复制的多行
IRow sourceRow = sheet.GetRow(1);
int sourceRowNum = sourceRow.RowNum;
int lastRowNum = sheet.LastRowNum;
int copyRowNum = lastRowNum - sourceRowNum;
//创建新行
IRow newRow = sheet.CreateRow(lastRowNum + 1);
//复制多行内容
for (int i = 0; i <= copyRowNum; i++)
{
//获取源行
sourceRow = sheet.GetRow(sourceRowNum + i);
//复制单元格
for (int j = 0; j < sourceRow.LastCellNum; j++)
题主,这个问题我来替你解决,若有帮助,还望采纳,点击回答右侧采纳即可。
1.涉及文件: NPOI.dll、NPOI.OOXML.dll、NPOI.OpenXml4Net.dll、NPOI.OpenXmlFormats.dll、NPOI.xml、ICSharpCode.SharpZipLib.dll
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
2.往EXCEL写数据、合并单元格、设置字体样式、插入图片
namespace Task_Test
{
public class ExcelHelper
{
public static void WriteExcel()
{
string templateFile = @"C:\test\temple.xlsx"; // 文件必须存在
string outFile = @"C:\test\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";
string picPath = @"C:\test\test.jpg";
IWorkbook workbook = null;
FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read);
if (Path.GetExtension(templateFile) == ".xls")
{
workbook = new HSSFWorkbook(file);
}
else if (Path.GetExtension(templateFile) == ".xlsx")
{
workbook = new XSSFWorkbook(file);
}
ISheet sheet = workbook.GetSheetAt(0);
try
{
SetCellValue(sheet, 0, 0, "这里是第1行第1列内容");
SetCellValue(sheet, 0, 1, "这里是第1行第2列内容");
SetCellValue(sheet, 1, 0, "这里是第2行第1列内容");
SetCellValue(sheet, 1, 1, "这里是第2行第2列内容");
// Height:单位是1/20个点,所以要想得到一个点的话,需要乘以20。
sheet.GetRow(1).Height = 44 * 20; // 给第2行设置行高
// Width: 单位是1/256个字符宽度,所以要乘以256才是一整个字符宽度
sheet.SetColumnWidth(1, 50 * 256); // 给第1列设置宽度
SetCellValue(sheet, 2, 0, "这里是第3行第1列内容,需要设置字体样式");
// 从第3行到第6行,第1列到第4列合并单元格
SetCellRangeAddress(sheet, 2, 5, 0, 3);
// 给合并之后的单元格加边框,并设置字体大小、居中、字体颜色、背景色
AddRengionBorder(workbook, sheet, 2, 5, 0, 3);
// 插入图片
InsertFootSignPic(workbook, sheet, 7, 16, 0, 2, outFile, picPath);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (file != null)
{
file.Close();
}
}
}
/// <summary>
/// 单元格设置内容
/// </summary>
/// <param name="sheet"></param>
/// <param name="rowIndex">第几行,从0开始</param>
/// <param name="cellIndex">第几列,从0开始</param>
/// <param name="value">内容(字符串)</param>
public static void SetCellValue(ISheet sheet, int rowIndex, int cellIndex, string value)
{
if (sheet.GetRow(rowIndex) == null)
{
sheet.CreateRow(rowIndex);
}
if (sheet.GetRow(rowIndex).GetCell(cellIndex) == null)
{
sheet.GetRow(rowIndex).CreateCell(cellIndex);
}
sheet.GetRow(rowIndex).GetCell(cellIndex).SetCellValue(value);
}
/// <summary>
/// 合并单元格
/// </summary>
/// <param name="sheet">要合并单元格所在的sheet</param>
/// <param name="rowstart">开始行的索引</param>
/// <param name="rowend">结束行的索引</param>
/// <param name="colstart">开始列的索引</param>
/// <param name="colend">结束列的索引</param>
public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
{
for (int r = rowstart; r <= rowend; r++)
{
for (int c = colstart; c <= colend; c++)
{
if (sheet.GetRow(r) == null)
{
sheet.CreateRow(r); // 如果行不存在,则创建行
}
if (sheet.GetRow(r).GetCell(c) == null)
{
sheet.GetRow(r).CreateCell(c); // 如果列不存在,则创建列
}
}
}
NPOI.SS.Util.CellRangeAddress cellRangeAddress = new NPOI.SS.Util.CellRangeAddress(rowstart, rowend, colstart, colend);
sheet.AddMergedRegion(cellRangeAddress);
}
/// <summary>
/// 加范围边框和设置字体大小、颜色、背景色、居中
/// </summary>
/// <param name="firstRow">起始行</param>
/// <param name="lastRow">结束行</param>
/// <param name="firstCell">起始列</param>
/// <param name="lastCell">结束列</param>
/// <returns></returns>
public static void AddRengionBorder(IWorkbook workbook, ISheet sheet, int firstRow, int lastRow, int firstCell, int lastCell)
{
for (int i = firstRow; i < lastRow; i++)
{
for (int n = firstCell; n < lastCell; n++)
{
ICell cell;
cell = sheet.GetRow(i).GetCell(n);
if (cell == null)
{
cell = sheet.GetRow(i).CreateCell(n);
}
ICellStyle style = sheet.Workbook.CreateCellStyle();
style.BorderTop = BorderStyle.Thin;
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.Alignment = HorizontalAlignment.Center; //水平对齐 :居中
style.VerticalAlignment = VerticalAlignment.Center; //垂直对齐 :居中
if (i == firstRow) //第一行
{
style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index; // 背景色:黑色
style.FillPattern = FillPattern.SolidForeground;
IFont font = workbook.CreateFont(); //创建一个字体颜色
font.Color = NPOI.HSSF.Util.HSSFColor.White.Index; //字体颜色:白色
font.FontHeightInPoints = 18;//字体大小
style.SetFont(font); //给样式设置字体
}
cell.CellStyle = style;
}
}
}
/// <summary>
/// 往EXCEL指定单元格插入图片
/// </summary>
/// <param name="workbook"></param>
/// <param name="sheet"></param>
/// <param name="firstRow"> 起始单元格行序号,从0开始计算</param>
/// <param name="lastRow"> 终止单元格行序号,从0开始计算</param>
/// <param name="firstCell"> 起始单元格列序号,从0开始计算</param>
/// <param name="lastCell"> 终止单元格列序号,从0开始计算</param>
/// <param name="outFile">插入图片后,另存为路径(绝对路径)</param>
/// <param name="picurl">图片绝对路径</param>
public static void InsertFootSignPic(IWorkbook workbook, ISheet sheet, int firstRow, int lastRow, int firstCell, int lastCell, string outFile, string picurl)
{
FileStream filess = null;
try
{
// 将图片转换为字节数组
byte[] bytes = System.IO.File.ReadAllBytes("" + picurl + "");
int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch();
// dx1:起始单元格的x偏移量,如例子中的255表示直线起始位置距A1单元格左侧的距离;
// dy1:起始单元格的y偏移量,如例子中的125表示直线起始位置距A1单元格上侧的距离;
// dx2:终止单元格的x偏移量,如例子中的1023表示直线起始位置距C3单元格左侧的距离;
// dy2:终止单元格的y偏移量,如例子中的150表示直线起始位置距C3单元格上侧的距离;
// col1:起始单元格列序号,从0开始计算;
// row1:起始单元格行序号,从0开始计算,如例子中col1 = 0,row1 = 0就表示起始单元格为A1;
// col2:终止单元格列序号,从0开始计算;
// row2:终止单元格行序号,从0开始计算,如例子中col2 = 2,row2 = 2就表示起始单元格为C3;
XSSFClientAnchor anchor = new XSSFClientAnchor(10, 10, 0, 0, firstCell, firstRow, lastCell, lastRow);
//把图片插到相应的位置
XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
filess = File.OpenWrite(outFile);
workbook.Write(filess);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (filess != null)
{
filess.Close();
}
}
}
}
}
3.运行后效果图