如何在Spire.XLS中克隆工作簿?

时间:2018-10-17 13:19:00

标签: c# excel spire.xls

我有一个要克隆的Spire.Xls.Workbook对象。由于该类不提供Clone方法,因此我尝试创建一个新工作簿并从现有工作簿复制所有现有工作表。这是我的代码:

public void Clone(Workbook workbook, string fileName)
{
    var clone = new Workbook();

    // copy worksheets to List to be able to use foreach
    var worksheets = workbook.Worksheets
        .Cast<Worksheet>()
        .ToList();

    foreach (Worksheet worksheet in worksheets)
    {
        var clonedSheet = worksheet.Clone(worksheet.Parent);
        clone.Worksheets.Add((IWorksheet)clonedSheet);
    }

    clone.SaveToFile(fileName, ExcelVersion.Version2007);
}

该方法完成,没有错误,创建了文件,但其中不包含任何克隆的工作表。我是在做错什么,还是无法创建Workbook对象的克隆?

2 个答案:

答案 0 :(得分:0)

使用:

    clone.Worksheets.AddCopy(worksheets);

答案 1 :(得分:0)

@DheerajMalik's answer适用于.xlsx文件。如果您有.xlsm个文件,则宏将丢失。要解决此限制,这是另一种方法:

using (var stream = new MemoryStream())
{
    // Save the original to a memory stream
    workbook.SaveToStream(stream);

    // Create a new workbook and load the content from the memory stream
    var clone = new Workbook();
    clone.LoadFromStream(stream);
}