1、读取函数
/// <summary>
/// 读取excel数据
/// </summary>
public DataSet ReadExcelFiles(string filePath,List<string> lSheetName)
{
string strConn = String.Format("Provider=Microsoft.Ace.OleDb.12.0;data source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'", filePath);
OleDbConnection conn = new OleDbConnection(strConn);
DataSet ds = new DataSet();
foreach (string sheetName in lSheetName)
{
try
{
OleDbDataAdapter adp = new OleDbDataAdapter("Select * from [" + sheetName + "$]", conn);
adp.Fill(ds, sheetName);
}
catch
{ throw; }
}
return ds;
}
2、函数调用
string filePath = Application.StartupPath + @"\路径下\数据.xlsx";
DataSet ds = ReadExcelFiles(filePath, new List<string>() { "数据" });
DataTable dt = ds.Tables["数据"];
if (dt != null)
{
//对数据进行处理
}