我想合并几个工作簿中的所有工作表,并将它们保存在一个excel文件中。我试图将所有工作表复制到一个工作簿中,然后将工作簿保存到文件中。问题是-仅将最后一张纸保存在文件中。下面是一些示例代码。
public static void ExportSheets(string documentFilePath, List<IWorkbook> workbooks)
{
if (workbooks.Count > 1)
{
var destinationSourceBook = workbooks[0];
for (int i = 1; i < workbooks.Count; i++)
{
var sourceWorkBook = workbooks[i];
for (int j = 0; j < sourceWorkBook.Sheets.Count; j++)
{
sourceWorkBook.Sheets[j].CopyAfter(destinationSourceBook.Sheets[destinationSourceBook.Sheets.Count - 1]);
}
}
destinationSourceBook.SaveAs(documentFilePath, FileFormat.OpenXMLWorkbook);
}
else if (workbooks.Count == 1)
{
workbooks[0].SaveAs(documentFilePath, FileFormat.OpenXMLWorkbook);
}
}
在调试时,我可以看到工作表已添加到destinationSourceBook.Sheets集合中,但是在保存的excel文件中仅存在最后一个工作表。正确的方法是什么?
谢谢
答案 0 :(得分:0)
实际上是在添加工作表,但是问题是“工作表”选项卡不可见(在excel中,“文件”->“选项”->“高级”->“显示选项”->“显示工作表”选项卡)。解决方案是将Workbook.WindowInfo.DisplayWorkbookTabs设置为true。
public static void ExportSheets(string documentFilePath, List<IWorkbook> workbooks)
{
if (workbooks.Count > 0)
{
var destinationWorkbook = workbooks[0];
for (var i = 1; i < workbooks.Count; i++)
{
var sourceWorkBook = workbooks[i];
for (var j = 0; j < sourceWorkBook.Sheets.Count; j++)
{
sourceWorkBook.Sheets[j].CopyAfter(destinationWorkbook.Sheets[destinationWorkbook.Sheets.Count - 1]);
}
}
destinationWorkbook.WindowInfo.DisplayWorkbookTabs = true;
destinationWorkbook.SaveAs(documentFilePath, FileFormat.OpenXMLWorkbook);
}
}