|
楼主 |
发表于 2013-8-22 13:34:16
|
显示全部楼层
根据各位高手的指点,写了下面代码,实现读取excel的sheet表某一列数据
#region 读取excel中一个表数据到DataSet
/**/
/// <summary>
/// 返回Excel数据源
/// </summary>
/// <param name="filename">文件路径</param>
/// <param name="TSql">TSql</param>
/// <returns>DataSet</returns>
public static DataSet ExcelToDataSet(string filename, string strCmd)
{
//连接字符串,连接excel文件
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filename;
//创建一个数据链接
OleDbConnection myConn = new OleDbConnection(strCon);
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCmd, myConn);
DataSet ds = new DataSet();
myCommand.Fill(ds);
myConn.Close();
return ds;
}
#endregion
#region 读取excel中某一数据表中某一列数据到listBox
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "工作表|*.xls";
ofd.ShowDialog();
string filename = ofd.FileName;
MessageBox.Show(filename);
//只要改表名,就可以读取不同表数据
//string TSql = "SELECT * FROM [" + tableName + "]";
string TSql = " SELECT * FROM [Sheet2$] ";
DataSet ds = ExcelToDataSet(filename, TSql);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
listBox1.Items.Add(ds.Tables[0].Rows[13]);
}
}
#endregion
|
|