我有一个要克隆的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
对象的克隆?
答案 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);
}