/// <summary>
/// ExcelHelper 辅助类 By Ahoo 2013-10-11
/// </summary>
public class ExcelHelper
{
/// <summary>
/// Excel加载进DataTable
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static DataTable ReadExcelToDateTable(string fileName)
{
string sConnectionString = GetConString(fileName);
using (OleDbConnection conn = new OleDbConnection(sConnectionString))
{
conn.Open();
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}
//从指定的表明查询数据,可先把所有表明列出来供用户选择
string strSql = "select * from [" + strTableNames[0] + "] ";
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(strSql, conn))
{
DataTable dt_Result = new DataTable();
dataAdapter.Fill(dt_Result);
return dt_Result;
}
}
} /// <summary>
/// 获取连接字符串
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private static string GetConString(string fileName)
{
return Path.GetExtension(fileName) == ".xlsx" ? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'" : "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
}
}
或者直接使用NPOI组件,该组件相当强大,就是中文API资源较少。
http://office.microsoft.com/zh-cn/excel/FX102602477.aspx