ITPub博客

首页 > Linux操作系统 > Linux操作系统 > C#中获取Excel文件中的表名

C#中获取Excel文件中的表名

原创 Linux操作系统 作者:iDotNetSpace 时间:2008-09-25 13:30:23 0 删除 编辑

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)); 

} 

} 

} 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-464294/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: c# oop思想
请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5765987