C# 获取Excel的sheet

gaohongtao_2005 2009-05-20 04:49:46
各位仁兄:
我想知道如何用C#获取Excel里面的sheet数量和名称
我用了这个代码
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;
}

但是返回的好像不对,其实这段代码我也不是很懂,请高人不吝赐教。
...全文
167 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
cppfaq 2009-05-20
  • 打赏
  • 举报
回复
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();
}
}
}

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧