以下网址的C#代码,说是获取excel所以表单的数据,但是为什么只能获取sheet1?
http://blog.csdn.net/mailun/article/details/8453038,不明白那个代码是控制选择不同的sheet的,而且该代码好像是从sh...
http://blog.csdn.net/mailun/article/details/8453038,不明白那个代码是控制选择不同的sheet的,而且该代码好像是从sheet1的第二行开始提取,第一行会忽略,这又是怎么回事?有人能讲解下嘛?
展开
1个回答
展开全部
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Excel files(*.xls)|*.xls;*.xlsx";//过滤一下,只要表格格式的
ofd.InitialDirectory = "c:\\";
ofd.RestoreDirectory = true;
ofd.FilterIndex = 1;
ofd.AddExtension = true;
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.ShowHelp = true;//是否显示帮助按钮
DataSet ds = new DataSet();//ds应该在这里new才对
if (ofd.ShowDialog() == DialogResult.OK)
{
string DBString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + ofd.FileName + ";Extended Properties=Excel 12.0";
OleDbConnection con = new OleDbConnection(DBString);
con.Open();
DataTable datatable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//获取表单,原始的是:Sheet1,Sheet2,Sheet3
for (int i = 0; i < datatable.Rows.Count; i++)
{
//获取表单的名字
String sheet = datatable.Rows[i][2].ToString().Trim();
OleDbDataAdapter ole = new OleDbDataAdapter("select * from [" + sheet + "]", con);
//DataSet ds = new DataSet(); //这个ds不要在这里new生成
ole.Fill(ds);
//输出表格里面的内容,我这里就两列数据,如果数据列数不确定就需要写循环了:Rows.Count
foreach (DataRow col in ds.Tables[0].Rows)
{
Console.WriteLine(col[0].ToString());
Console.WriteLine(col[1].ToString());
}
}
con.Close();
}
追问
追答
if (ofd.ShowDialog() == DialogResult.OK)
{
//获取表单,原始的是:Sheet1,Sheet2,Sheet3
for (int i = 0; i < datatable.Rows.Count; i++)
{
//获取表单的名字
String sheet = datatable.Rows[i][2].ToString().Trim();
OleDbDataAdapter ole = new OleDbDataAdapter("select * from [" + sheet + "]", con);
ole.Fill(ds);
}
con.Close();
}
Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
foreach (DataTable table in ds.Tables)
{
if (!data.ContainsKey(table.TableName))
{
data.Add(table.TableName, new List<string>());
}
for (int i = 0; i < table.Rows.Count; i++)
{
string temp = string.Empty;
for (int j = 0; j < table.Columns.Count; j++)
{
temp += string.Format("{0},", table.Rows[i][j].ToString());
}
data[table.TableName].Add(temp.Substring(0,temp.LastIndexOf(",")));
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询