【问题标题】:Merge multiple Excel sheets into one sheet将多个 Excel 工作表合并为一张工作表
【发布时间】:2022-01-06 13:59:48
【问题描述】:

我正在使用GemBox.Spreadsheet处理一些Excel文件,现在我需要将它们合并到一个文件中。
我知道怎么做sheets copying,但这会导致多张纸。我需要的是一个输出表,其中包含所有这些,一个接一个。

目前我正在做的是将每张工作表导出为DataTable,然后一一导入:

string[] files = { "Book1.xlsx", "Book2.xlsx", "Book3.xlsx" };

var destination = new ExcelFile();
var destinationSheet = destination.Worksheets.Add("Sheets");
int startRow = 0;

foreach (string file in files)
{
    var source = ExcelFile.Load(file);
    foreach (var sourceSheet in source.Worksheets)
    {
        var table = sourceSheet.CreateDataTable(new CreateDataTableOptions());
        destinationSheet.InsertDataTable(table, new InsertDataTableOptions() { StartRow = startRow });
        startRow += table.Rows.Count;
    }
}

destination.Save("Merged Output.xlsx");

但是这样一来,我就失去了单元格样式和文本格式。
有什么方法可以保留DataTable 的风格吗?

【问题讨论】:

  • 在这里搜索会给你很多可能性,这是一个:stackoverflow.com/q/30575923/4961700
  • @SolarMike 该代码使用 Excel 互操作,我不能使用它。
  • “该代码使用 Excel 互操作”?你们是什么人?

标签: c# excel gembox-spreadsheet


【解决方案1】:

为此,您可以使用CellRange.CopyTo 方法,如下所示:

string[] files = { "Book1.xlsx", "Book2.xlsx", "Book3.xlsx" };

var destination = new ExcelFile();
var destinationSheet = destination.Worksheets.Add("Sheets");

foreach (string file in files)
{
    var source = ExcelFile.Load(file);
    foreach (var sourceSheet in source.Worksheets)
    {
        var range = sourceSheet.GetUsedCellRange(true);
        range.CopyTo(destinationSheet, destinationSheet.Rows.Count, 0);
    }
}

destination.Save("Merged Output.xlsx");

请注意,CopyTo 只会复制单元格的值和样式。

但如果需要,您也可以使用类似的方法来复制列宽和行高。

string[] files = { "Book1.xlsx", "Book2.xlsx", "Book3.xlsx" };

var destination = new ExcelFile();
var destinationSheet = destination.Worksheets.Add("Sheets");

int lastColumn = 0;
foreach (string file in files)
{
    var source = ExcelFile.Load(file);
    foreach (var sourceSheet in source.Worksheets)
    {
        var range = sourceSheet.GetUsedCellRange(true);
        int startRow = destinationSheet.Rows.Count;
        range.CopyTo(destinationSheet, startRow, 0);

        for (int r = 0; r < range.Height; r++)
            destinationSheet.Rows[r + startRow].Height = sourceSheet.Rows[r].Height;

        for (; lastColumn < range.Width; lastColumn++)
            destinationSheet.Columns[lastColumn].Width = sourceSheet.Columns[lastColumn].Width;
    }
}

destination.Save("Merged Output.xlsx");

如果需要,您也可以使用this answer 复制图像。

您也可以使用相同的解决方案来复制形状和图表,它们都具有您需要在复制后调整的 Position 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多