100分求解决:datagridview打开Excel报错:名为“ClampVal”的列已属于此 DataTable。
在网上copy了份datagridview打开Excel的代码,打开Excel报错:名为“ClampVal”的列已属于此 DataTable。
Columns 不允许列名相同,但我又不能变更Excel数据.ClampVal列我也没显示在datagridview控件上,请问下有什么解决办法可以正常打开excel?
if (openFileDialog1.ShowDialog() == DialogResult.OK) //OK表示按下了“打开”
{
string s = null;
DataTable table = new DataTable("auto");
DataRow row = null;
String[] split = null;
using (StreamReader sr = new StreamReader(openFileDialog1.FileName, UnicodeEncoding.GetEncoding("GB2312")))
{
s = sr.ReadLine();
split = s.Split(',');
int i = 0;
foreach (String colname in split)
{
//名为“ClampVal”的列已属于此 DataTable。
table.Columns.Add(colname, System.Type.GetType("System.String"));
i++;
}
int j = 0;
while (sr.Peek() > -1)
{
s = sr.ReadLine();
j = 0;
row = table.NewRow();
split = s.Split(',');
foreach (String colname in split)
{
row[j] = colname;
j++;
if (j >= i) { break; }
}
table.Rows.Add(row);
}
dataGridView1.DataSource = table.DefaultView;
sr.Close();
}
[最优解释]
foreach (String colname in split)
{
//名为“ClampVal”的列已属于此 DataTable。
//在这里加上判断,判断列名是否存在
if (!table.Columns.Contains(colname)) {
table.Columns.Add(colname, System.Type.GetType("System.String"));
i++;
}
}
[其他解释]
有一个相同的列名啦!!! LZ 赶快修改一下吧!! 修改一下就 OK 啦!!!
[其他解释]
if (table.Columns.Contains(colname))
continue;
[其他解释]
怎么可能有个相同的列名,修改下就行了。用不了这么多积分的。