获得Excle工作表数组
/// <summary>获得Excle工作表名称数组</summary>
/// <param name="filePath">文件路径</param>
/// <returns>ArrayList集合</returns>
public ArrayList GetExcleSheetName(string filePath)
{
ArrayList al = new ArrayList();
string connStr = "";
string fileType = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileType)) return null;
if (fileType == ".xls")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = null;
DataSet ds = new DataSet();
try
{
// 初始化连接,并打开
conn = new OleDbConnection(connStr);
conn.Open();
// 获取数据源的表定义元数据
DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
conn.Close();
foreach (DataRow dr in sheetNames.Rows)
{
al.Add(dr[2]);
}
}
catch
{ }
finally
{
// 关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
}
}
return al;
}
读取某张工作表
/// <summary>读取Excle数据表到DataTable</summary>
/// <param name="sheetName">工作表名称</param>
/// <param name="ExclePath">连接字符串</param>
/// <returns></returns>
public DataTable ReadExcle(string sheetName, string ExclePath)
{
string strConn = GetConnString(ExclePath);
if (string.IsNullOrEmpty(strConn))
{
return null;
}
else
{
using (OleDbConnection conn = new OleDbConnection(strConn))
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [" + sheetName + "]";
OleDbDataAdapter oledbda = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
oledbda.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
return ds.Tables[0];
}
else
{
return null;
}
}
}
}
}
获得Excle连接字符串
/// <summary>获得Excle数据表连接字符串</summary>
/// <param name="Exclepath">Excle路径</param>
/// <returns></returns>
public string GetConnString(string ExclePath)
{
if (string.IsNullOrEmpty(ExclePath) || (!System.IO.File.Exists(ExclePath))) { return null; }
string extension = System.IO.Path.GetExtension(ExclePath);
if (extension == ".xls")
{
return "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + ExclePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
}
else
{
return "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + ExclePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
}
}
要导入的命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;//DataTable等
using System.Data.OleDb;//Excle连接用发送命令等
using System.Collections;//当中用的ArrayList集合
付上---Excle操作链接,别人写的