天天看点

C#从Excel文件中读取数据转换为DataSet

1. 打开文件获取到FilePath;

2. 读取Sheet名称TABLENAME;

3. 将数据Fill到DataSet中;

public DataSet ExcelToDataSet(string filePath, string TABLENAME)
{
	string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
	OleDbConnection conn = new OleDbConnection(strConn);
	conn.Open();
	
	string strExcel = "";
	DataSet ds = new DataSet();
	
	strExcel = "select * from [" + TABLENAME + "$]";
	OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
	myCommand.Fill(ds, "table1");

	return ds;
}