//// <summary>
/// 读取Excel文件,将内容存储在DataSet中
/// </summary>
/// <param name="opnFileName">带路径的Excel文件名</param>
/// <returns>DataSet</returns>
private DataSet ExcelToDataSet(string FileName, string SheetName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
string strExcel = string.Format("Select * from [{0}$]", SheetName);
OleDbDataAdapter myCommand = null;
DataSet ds = new DataSet();
try
{
conn.Open();
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds,"dtSource");
return ds;
}
catch (Exception ex)
{
MessageBox.Show(string.Format("导入Excel文件出错!\r\n\r\n错误信息: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return ds;
}
finally
{
conn.Close();
conn.Dispose();
}
}供参考...
(1) string sheetname = "[Sheet1$]";
(2) string path = "d:\\csdn.xls";
private void button4_Click(object sender, EventArgs e)
{
string sheetname = "[Sheet1$]";
DataSet ds = new DataSet();
string path = "d:\\csdn.xls";
string sqltext = "select * from " + sheetname.Trim().ToString(); string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';" +
"data source=" + path; OleDbConnection connection = new OleDbConnection(connstr);
try
{
connection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(sqltext, connection);
adapter.Fill(ds, "sheet");
this.dataGridView1.DataSource = ds;
this.dataGridView1.DataMember = "sheet";
}
catch (OleDbException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connection.Close();
connection.Dispose();
}
}
OracleConnection con = new OracleConnection("server=ORCL;user id=scott;password=tiger");
OracleCommand cmd = new OracleCommand("select * from studentinfo", con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
using(OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
OleDbDataAdapter myCommand = null;
DataSet ds = null;
string strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
}