How C # Gets a collection of sheet pages (worksheets) in an Excel workbook

Source: Internet
Author: User
Tags tostring
#region get a collection of sheet pages (sheets) in an Excel workbook
02.///<summary>
03.///get a collection of sheet pages (worksheets) in an Excel workbook
04.///</summary>
05.///<param name= "excelfile" >excel filename and path, eg:c:\users\jk\desktop\ import Test .xls</param>
06.///<returns>sheet page Name Collection </returns>
07.private string[] Getexcelsheetnames (String fileName)
08.{
OleDbConnection objconn = null;
System.Data.DataTable dt = null;
One try.
12. {
String connstring=string. Empty;
String FileType =filename.substring (Filename.lastindexof ("."));
if (FileType = ". xls")
connstring = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data source=" + FileName + "; Extended Properties=excel 8.0; ";
Else//.xlsx
connstring = "provider=microsoft.ace.oledb.12.0" + "Data source=" + FileName + ";" + "; Extended properties=\ "Excel 12.0; Hdr=yes;imex=1\ "";
20.//Create Connection object
objconn = new OleDbConnection (connstring);
22.//Open database connection
objConn.Open ();
24.//Get data table containing data schema
DT = objconn.getoledbschematable (OleDbSchemaGuid.Tables, NULL);
if (dt = null)
27. {
return null;
29.}
string[] excelsheets = new String[dt. Rows.Count];
int i = 0;
32.//Add sheet name to string array
foreach (DataRow row in dt. Rows)
34. {
String strsheettablename = row["table_name"]. ToString ();
36.//Filter Invalid SheetName
Strsheettablename.contains ("$") &&strsheettablename.replace ("'", ""). EndsWith ("$"))
38. {
Excelsheets[i] = strsheettablename.substring (0, strsheettablename.length-1);
40.}
i++;
42.}
Excelsheets return;
44.}
catch (Exception ex)
46. {
MessageBox.Show (ex. ToString ());
return null;
49.}
Finally
51. {
52.//Clean up
if (objconn!= null)
54. {
Objconn.close ();
Objconn.dispose ();
57.}
!=. if (DT-null)
59. {
DT. Dispose ();
61.}
62.}
63.}
#endregion

This paper url:http://www.bianceng.cn/programming/csharp/201410/45597.htm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.