Achill
unread,Dec 29, 2008, 8:34:41 PM12/29/08Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to group
我们都知道在excel文件中第一个表名的缺省值是sheet1$, 但有时工作的需要也会被改为其他名字. 如果需要在C#中使用OleDb读写Excel文件, 就需要知道这个名字是什么. 以下代码就是实现这个功能的,具体如下:
using System;
using System.IO;
using System.Data;
using System.Data.OleDb;
namespace Skyiv.Ben.Util
{
sealed class Pub
{
public static string GetExcelFirstTableName(string excelFileName)
{
string tableName = null;
if (File.Exists(excelFileName))
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet."+
"OLEDB.4.0;Extended Properties=\"Excel 8.0\";Data Source=" + excelFileName))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
tableName = dt.Rows[0][2].ToString().Trim();
}
}
return tableName;
}
}
}
namespace Skyiv.Ben.Test
{
using Skyiv.Ben.Util;
class MainTest
{
static void Main(string [] args)
{
foreach (string s in args)
Console.WriteLine("[{0}] => [{1}]", s, Pub.GetExcelFirstTableName(s));
}
}
}
Sincerely
Achilles