A friend asked:
Code Public ArrayList ExcelSheetName (string filepath)
{
ArrayList al = new ArrayList ();
String strConn;
StrConn = "Provider = Microsoft. jet. OLEDB.4.0; Data Source = "+ filepath +"; Extended Properties = \ "Excel 8.0; HDR = Yes; IMEX = 1 ;\";";
OleDbConnection conn = new OleDbConnection (strConn );
Conn. Open ();
DataTable sheetNames = conn. GetOleDbSchemaTable
(System. Data. OleDb. OleDbSchemaGuid. Tables, new object [] {null, "TABLE "});
Conn. Close ();
Foreach (DataRow dr in sheetNames. Rows)
{
Al. Add (dr [2]);
}
Return al;
}
The EXCEL table names obtained in this method are alphabetically arranged. If I want to obtain the first worksheet name in EXCEL, what should I do?
In fact, using the Excel object model provided by the Framework can easily solve this problem. The following is the testing process and code of the invitation month:
Create a console project and add two dll
Microsoft. Office. Interop. Excel
Microsoft. VisualBasic
Add code:
Using System;
Using System. Collections. Generic;
Using System. Text;
// Add namespace
Using Microsoft. Office. Interop. Excel;
Namespace ReadFirstSheetNameDemo
{
Public class Program
{
Public static void Main (string [] args)
{
// Get Xth SheetName of Excel File
Console. WriteLine (GetFirstSheetNameFromExcelFileName ("C: \ test.xls", 1 ));
Console. ReadKey ();
}
Public static string GetFirstSheetNameFromExcelFileName (string filepath, int numberSheetID)
{
If (! System. IO. File. Exists (filepath ))
{
Return "This file is on the sky ?? ";
}
If (numberSheetID <= 1) {numberSheetID = 1 ;}
Try
{
Microsoft. Office. Interop. Excel. Application obj = default (Microsoft. Office. Interop. Excel. Application );
Microsoft. Office. Interop. Excel. Workbook objWB = default (Microsoft. Office. Interop. Excel. Workbook );
String strFirstSheetName = null;
Obj = (Microsoft. Office. Interop. Excel. Application) Microsoft. VisualBasic. Interaction. CreateObject ("Excel. Application", string. Empty );
ObjWB = obj. Workbooks. Open (filepath, Type. Missing, Type. Missing,
Type. Missing,
Type. Missing,
Type. Missing, Type. Missing );
StrFirstSheetName = (Microsoft. Office. Interop. Excel. Worksheet) objWB. Worksheets [1]). Name;
ObjWB. Close (Type. Missing, Type. Missing, Type. Missing );
ObjWB = null;
Obj. Quit ();
Obj = null;
Return strFirstSheetName;
}
Catch (Exception Err)
{
Return Err. Message;
}
}
}
}
Result:
References:
Http://www.cnblogs.com/downmoon/archive/2008/08/20/1272185.html
Http://msdn.microsoft.com/zh-cn/library/aa168292%28office.11%29.aspx#EDAA