posts - 315, comments - 268, trackbacks - 15

My Links

News

View Pietro Libro's profile on LinkedIn

DomusDotNet
   DomusDotNet

Pietro Libro

Tag Cloud

Article Categories

Archives

Post Categories

Blogs amici

Links

GetOleDbSchemaTable e fogli di lavoro di un file Excel

Post nato da una discussione su forum. Per recuperare i nomi degi fogli di lavoro di un file excel, al fine di popolare ( ad esempio) un controllo ComboBox, possiamo sfruttare la funzione GetOleDbSchemaTable della classe OleDbConnection, la quale, restituisce un istanza di oggetto DataTable con le informazioni a noi necessarie. Il codice per popolare il ComboBox è il seguente:

1 DataTable dt = GetWorksheetList(@"C:\Test.xls");
2 if (dt != null)
3 {
4 comboBox1.DisplayMember = "TABLE_NAME";
5 comboBox1.DataSource = dt;
6 }

mentre la funzione GetWorksheetList è la seguente:

1 private DataTable GetWorksheetList(string pathAndFileName)
2 {
3 DataTable workSheetsDataTable = null ;
4 5 using (OleDbConnection connection = new OleDbConnection())
6 {
7 string connectionString = string.Format(
8 @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;",
9 pathAndFileName );
10 11 connection.ConnectionString = connectionString;
12 13 try 14 {
15 connection.Open();
16 17 workSheetsDataTable= connection.GetOleDbSchemaTable(
18 System.Data.OleDb.OleDbSchemaGuid.Tables ,
19 new object[] { null, null, null, "TABLE" });
20 21 connection.Close();
22 }
23 catch (Exception ex)
24 {
25 26 MessageBox.Show("Attenzione:" + ex.Message);
27 }
28 }
29 return workSheetsDataTable ;
30 }
Technorati Tag: ,

Print | posted on giovedì 21 febbraio 2008 14:27 | Filed Under [ C# ]

Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET