读取Excel里面的内容转为DataTable
Posted mact
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取Excel里面的内容转为DataTable相关的知识,希望对你有一定的参考价值。
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Text; namespace ExcelRead { class ExcelHelper { private static string excelConstr; private OleDbConnection conn = null;//操作数据库 private OleDbDataAdapter ada = null;//填充dataset public ExcelHelper(string path) { excelConstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties = Excel 12.0"; if (conn == null || conn.State == ConnectionState.Closed) { conn = new OleDbConnection(excelConstr); } } public DataTable GetDataSource(string sheetName) { DataTable dt = new DataTable(); string sql = string.Empty; sql = "select * from [" + sheetName + "]"; dt = GetDT(sql); return dt; } /// <summary> /// 获取excel数据 /// </summary> /// <param name="sql">用于查询的sql</param> /// <returns></returns> public DataTable GetDT(string sql) { DataSet ds = new DataSet(); try { if (conn.State == ConnectionState.Closed) { conn.Open(); } ada = new OleDbDataAdapter(sql, conn); ada.Fill(ds); } catch (Exception e) { throw e; } finally { conn.Close(); } return ds.Tables[0]; } } }
//获取Excel表里Sheet1的数据
//调用 ExcelHelper _excelhelper = new ExcelHelper("Excel文件路径"); //Excel的sheet名称,后面要跟$符号 _excelhelper.GetDataSource("Sheet1$");
以上是关于读取Excel里面的内容转为DataTable的主要内容,如果未能解决你的问题,请参考以下文章