C#读取Excel文件

时间:2024-10-29 00:06:08
          //excel模板的路径
string strSource = Application.StartupPath + "\\" + "ExcelTemplet" + ".xls"; DataTable dtGetExcel = new DataTable(); dtGetXls = XlsToDataTable(strSource); /// <summary>
/// 将Excel中的数据导入到DataTable中,获取EXCEL中列的顺序
/// </summary>
/// <param name="strpath">excel模板的路径</param>
/// <returns></returns>
private DataTable XlsToDataTable(String strpath)
{
string strConn;
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'",strpath); OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
DataTable dt = new DataTable();
myCommand.Fill(dt);
conn.Close(); return dt;
}