在 Excel 个文件中复制包含图像的单元格范围

Copying cell range with images in Excel files

我正在使用 GemBox.Spreadsheet 将一个 Excel sheet 的单元格复制到另一个 GemBox.Spreadsheet。这些单元格来自特定的命名范围,我正在使用 CellRange.CopyTo 方法,如下所示:

ExcelFile book = ExcelFile.Load("sv-data.xlsx");
ExcelWorksheet sheet1 = book.Worksheets[0];
CellRange range1 = sheet1.NamedRanges["SV"].Range;
ExcelWorksheet sheet2 = book.Worksheets.Add("Sheet2");
range1.CopyTo(sheet2, 14, 3);

这对所有单元格的值和格式都很有效,但它不会复制图像。

这是预期的行为吗?如何同时复制数据和图像?

是的,这似乎是有意为之,因为图像不是存储在单元格内,而是存储在 sheet 内。它们是单独集合 ExcelWorksheet.Pictures.

的一部分

因此,也许您可​​以遍历该集合并复制所需的元素。

例如,如下所示:

ExcelFile book = ExcelFile.Load("sv-data.xlsx");
ExcelWorksheet sheet1 = book.Worksheets[0];
CellRange range1 = sheet1.NamedRanges["SV"].Range;

ExcelWorksheet sheet2 = book.Worksheets.Add("Sheet2");

int row2 = 14;
int column2 = 3;
range1.CopyTo(sheet2, row2, column2);

int rowOffset = row2 - range1.FirstRowIndex;
int columnOffset = column2 - range1.FirstColumnIndex;

foreach (ExcelPicture picture1 in sheet1.Pictures)
{
    ExcelDrawingPosition position1 = picture1.Position;
    CellRange pictureRange1 = sheet1.Cells.GetSubrangeAbsolute(position1.From.Row.Index, position1.From.Column.Index, position1.To.Row.Index, position1.To.Column.Index);

    if (range1.Overlaps(pictureRange1))
    {
        ExcelPicture picture2 = sheet2.Pictures.AddCopy(picture1);
        ExcelDrawingPosition position2 = picture2.Position;

        position2.From.Row = sheet2.Rows[position2.From.Row.Index + rowOffset];
        position2.To.Row = sheet2.Rows[position2.To.Row.Index + rowOffset];
        position2.From.Column = sheet2.Columns[position2.From.Column.Index + columnOffset];
        position2.To.Column = sheet2.Columns[position2.To.Column.Index + columnOffset];
    }
}

book.Save("output.xlsx");