您的位置:首页 > 编程语言 > C#

C#遍历DataSet中数据的几种方法总结

2015-06-29 10:40 661 查看
//多表多行多列的情况

foreach (DataTable dt in YourDataset.Tables) //遍历所有的datatable

{

foreach (DataRow dr in dt.Rows) ///遍历所有的行

foreach (DataColumn dc in dt.Columns) //遍历所有的列

Console.WriteLine("{0}, {1}, {2}", dt.TableName, dc.ColumnName, dr[dc]); //表名,列名,单元格数据

}

//遍历一个表多行多列

foreach(DataRow mDr in dataSet.Tables[0].Rows)

{

foreach(DataColumn mDc in dataSet.Tables[0].Columns)

{

Console.WriteLine(mDr[mDc].ToString());

}

}

//遍历一个表多行一列

foreach(DataRow row in DataSet1.Tables[0].Rows)

{

Console.WriteLine(row[0].ToString());

}

//一行一列

ds.Tables[0].Rows[0]["字段"];

示例:

private DataSet GetDataSet(string fileName, string sheetName)

{

DataSet ds = new DataSet();

string filePath = fileName;

string connStr = "";

string fileType = System.IO.Path.GetExtension(fileName);

if (string.IsNullOrEmpty(fileType))

{

return null;

}

if (fileType == ".xls")

{

connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";

}

else if (fileType == ".xlsx")

{

connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";

}

string sql_F = "Select * FROM [{0}]";

OleDbConnection conn = null;

OleDbDataAdapter da = null;

DataTable dtSheetName = null;

try

{

// 初始化连接,并打开

conn = new OleDbConnection(connStr);

conn.Open();

// 获取数据源的表定义元数据

string SheetName = "";

dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

// 初始化适配器

da = new OleDbDataAdapter();

for (int i = 0; i < dtSheetName.Rows.Count; i++)

{

SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];

if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))

{

continue;

}

cmbSheet.Items.Add(SheetName);

if (SheetName != sheetName)

{

continue;

}

da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);

DataSet dsItem = new DataSet();

da.Fill(dsItem, SheetName);

ds.Tables.Add(dsItem.Tables[0].Copy());

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

return null;

}

finally

{

// 关闭连接

if (conn.State == ConnectionState.Open)

{

conn.Close();

da.Dispose();

conn.Dispose();

}

}

return ds;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: