天天看點

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;
}