使用这里的例子
How to Copy a Worksheet within a Workbook
我已经成功地能够在我的excel文件中克隆/复制工作表,但是当我打开excel时,第二张工作表是活动(可见)工作表.我无法找到一个可以做什么的属性…..有没有办法指定哪些工作表是活动的?
我试图通过打开和编辑文件中的第一张纸来强制它,认为它是最后编辑的工作表,但是也没有用.
任何帮助都会很棒. TIA
更新:查看将.xlsx重命名为.zip时创建的workbook.xml我遇到了’activeTab’属性.快速更改我的代码,似乎工作得很好
public void SetFirstSheetInFocus(String xlsxFile) { using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(xlsxFile,true)) { //Get a reference to access the main Workbook part,which contains all references WorkbookPart _workbookPart = spreadSheet.WorkbookPart; if (_workbookPart != null) { WorkbookView _workbookView = spreadSheet.WorkbookPart.Workbook.BookViews.ChildElements.First<WorkbookView>(); if (_workbookView != null) { _workbookView.ActiveTab = 0; // 0 for first or whatever tab you want to use } // Save the workbook. _workbookPart.Workbook.Save(); } } }
解决方法
如果工作表的名称在变量中
sheetName
您可以将具有该名称的工作表设置为活动,如下所示:
using (var spreadsheetDoc = SpreadsheetDocument.Open(emptyHIPTemplatePath,true /* isEditable */,new OpenSettings { AutoSave = false })) { var workbookPart = spreadsheetDoc.WorkbookPart; var workBook = spreadsheetDoc.WorkbookPart.Workbook; var sheet = workBook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName); var sheetIndex = workBook.Descendants<Sheet>().ToList().IndexOf(sheet); var workBookView = workBook.Descendants<WorkbookView>().First(); workBookView.ActiveTab = Convert.ToUInt32(sheetIndex); ... workBook.Save(); }