打开MS Excel工作表在C# [英] Opening MS Excel worksheet in C#
问题描述
我知道我们可以通过提供张数(1,2,3 ...)或名称(Sheet1中,Sheet2中,工作表Sheet 3 ...)
I know we can open a particular worksheet of MS Excel using C# by providing the sheet number (1,2,3..) or name (sheet1, sheet2, sheet3...)
我有2张,1值,2结果
I have a excel file which has 2 sheets, 1. Values, 2. Results
有没有办法打开一个表给表一个excel文件名称,即价值,而不是1或[S | S] heet1在C#??
Is there a way to open a sheet giving the sheet name ,i.e, "Values" instead of 1 or [s|S]heet1 in C# ??
我看着直通旧的职位,但没有发现任何有用的东西......
I looked thru the old posts but didnt find anything useful...
如此反复,我所试图做的是,通过使用它的用户定义的名称(值)打开一个Excel工作表,而不是系统定义的名称(1或[S |!S] heet1)
so again, what I am trying to do is, open a Excel worksheet by using its user defined name (Values) instead of the system defined name(1 or [s|S]heet1)
任何输入将不胜感激。
推荐答案
要添加的Microsoft.Office.Interop.Excel引用在您的项目,你可以使用下面的代码为基础
Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; // prevents message from popping up
try
{
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, 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));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
int nCounter = 1;
oSheet.Copy(oSheet, Type.Missing);
Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
oSheetGame.Name = "MyNewWorksheetName";
// do something with worksheet
((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();
}
catch (Exception e)
{
//throw e;
throw;
}
finally
{
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
oXL.Save(Type.Missing);
这篇关于打开MS Excel工作表在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!