public static OleDbConnection GetExcleConnection(string viFilePath,string viExcelFileName)
{ string nExtension = Path.GetExtension(viExcelFileName); if (nExtension != ".xls" && nExtension != ".xlsx") { throw new Exception("未指定Excel类型"); } else { string nExcelConn = ""; if (nExtension == ".xls") { // Excel 97-2003 nExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.Combine(viFilePath, viExcelFileName) + ";Extended Properties='Excel 8.0;HDR=YES;'"; } else { // Excel 2007 nExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path.Combine(viFilePath, viExcelFileName) + ";Extended Properties='Excel 12.0 Xml;HDR=YES;'"; } return new OleDbConnection(nExcelConn); }}
public static OleDbCommand GetExcelCommand(string viFilePath, string viExcelFileName) { OleDbCommand nCommand = new OleDbCommand(); nCommand.Connection = GetExcleConnection(viFilePath, viExcelFileName); return nCommand; }