How to get the sheet name from an excel file in c#.net?
- Thank you for replying
解答
以 C# 取得 excel 檔中各個 sheet name 的方法如下:
1. 建立並打開 OleDBConnection
2. 以 OleDBConneciton.GetOleDbSchemaTable 取得 data table
3. 以 DataRow["TABLE_NAME"] 取出 sheet name
4. 關閉並釋放 OleDBConnection
範例程式如下
Code Snippetusing System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;namespace ExcelSheet
{
class Program
{
static void Main(string[] args)
{
OleDbConnection objConn = null;
DataTable dataTable = null;
try
{// connection string
String connString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ "D:\\Excel.xlsx" +
";Extended Properties=Excel 12.0;";// Create and Open OleDbConnection
objConn = new OleDbConnection(connString);
objConn.Open();// Get the data table
dataTable =
objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
null);
if(dataTable == null)
{
Console.WriteLine("no table");
}foreach(DataRow row in dataTable.Rows)
{// Write the sheet name to the screen
Console.WriteLine(row["TABLE_NAME"].ToString());
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{// Close and dispose the connection
if(objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if(dataTable != null)
{
dataTable.Dispose();
}
}
}
}
}Wade Lin
所有回覆
以 C# 取得 excel 檔中各個 sheet name 的方法如下:
1. 建立並打開 OleDBConnection
2. 以 OleDBConneciton.GetOleDbSchemaTable 取得 data table
3. 以 DataRow["TABLE_NAME"] 取出 sheet name
4. 關閉並釋放 OleDBConnection
範例程式如下
Code Snippetusing System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;namespace ExcelSheet
{
class Program
{
static void Main(string[] args)
{
OleDbConnection objConn = null;
DataTable dataTable = null;
try
{// connection string
String connString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ "D:\\Excel.xlsx" +
";Extended Properties=Excel 12.0;";// Create and Open OleDbConnection
objConn = new OleDbConnection(connString);
objConn.Open();// Get the data table
dataTable =
objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
null);
if(dataTable == null)
{
Console.WriteLine("no table");
}foreach(DataRow row in dataTable.Rows)
{// Write the sheet name to the screen
Console.WriteLine(row["TABLE_NAME"].ToString());
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{// Close and dispose the connection
if(objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if(dataTable != null)
{
dataTable.Dispose();
}
}
}
}
}Wade Lin
謝謝回覆

