[英]Open Excel File on a specific worksheet
I have an Excel file with 5 worksheets and I want with c# code to open it and when it is opened I want the sheet number 3 to be activated. 我有一个带有5个工作表的Excel文件,我希望用c#代码打开它,当它打开时,我希望激活工作表编号3。
How can I do that? 我怎样才能做到这一点?
Like this: 像这样:
using Excel;
Excel.Application excelApp = new Excel.ApplicationClass();
// if you want to make excel visible to user, set this property to true, false by default
excelApp.Visible = true;
// open an existing workbook
string workbookPath = "c:/SomeWorkBook.xls";
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
// get all sheets in workbook
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
// get some sheet
string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet =
(Excel.Worksheet)excelSheets.get_Item(currentSheet);
// access cell within sheet
Excel.Range excelCell =
(Excel.Range)excelWorksheet.get_Range("A1", "A1");
Hope this helps 希望这可以帮助
What about something like this: (untested) 这样的事情:(未经测试)
//using Excel = Microsoft.Office.Interop.Excel;
Excel.ApplicationClass app = new Excel.ApplicationClass();
Excel.Workbook workbook = app.Workbooks.Open("YourFile.xls",
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Number 3"];
worksheet.Activate();
If wanting to present visual feedback to the User, these two statements will set the activated sheet and select the range accordingly: 如果想要向用户呈现视觉反馈,这两个语句将设置激活的工作表并相应地选择范围:
Consider including the following statement immediately prior to initializing the Excel.Range... 在初始化Excel.Range之前,请考虑包含以下语句...
// Set Active sheet in Excel //在Excel中设置活动工作表
excelWorksheet.Activate() excelWorksheet.Activate()
Also consider the following statement immediately after initializing the Excel.Range... 初始化Excel.Range后立即考虑以下语句...
// Set Active range in Excel //在Excel中设置活动范围
excelCell.Activate() excelCell.Activate()
public static Workbook openExternalWorkBook(String fileName)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;
return excel.Workbooks.Open(fileName, false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.