111,125
社区成员
发帖
与我相关
我的任务
分享public static System.Data.DataTable GetExcelTableNames(string filename)
{
System.Data.DataTable dt = new System.Data.DataTable();
OleDbConnection cnnxls = new OleDbConnection();
try
{
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ;Extended Properties=Excel 8.0;Data Source =" + filename;
cnnxls.ConnectionString = mystring;
cnnxls.Open();
dt = cnnxls.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
}
finally
{
cnnxls.Close();
}
return dt;
}using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Net;
using System.Xml;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main()
{
string[] names = GetExcelTableNames("temp.xls");
if (names == null || names.Length == 0)
{
Console.WriteLine("Bad excel file or no sheet is available!");
return;
}
Console.WriteLine("There are {0} sheet(s):", names.Length);
foreach (string excelTableName in GetExcelTableNames("temp.xls"))
{
Console.WriteLine("\t" + excelTableName);
}
Console.ReadLine();
}
public static string[] GetExcelTableNames(string filename)
{
DataTable dt = new DataTable();
OleDbConnection cnnxls = new OleDbConnection();
try
{
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ;Extended Properties=Excel 8.0;Data Source =" +
filename;
cnnxls.ConnectionString = mystring;
cnnxls.Open();
dt = cnnxls.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
}
finally
{
cnnxls.Close();
}
List<string> names = new List<string>();
foreach (DataRow row in dt.Rows)
{
names.Add(row["TABLE_NAME"].ToString().Trim('\'', '$').Replace("''", "'").Replace("$$", "$"));
}
return names.ToArray();
}
}
}