我试图在Excel工作表中选择总计的总和,然后将其添加到一个列表框中,每一个都在一个新行中。
private void btn_update_Click(object sender, EventArgs e) {
for (int i = list_sheetnames.Items.Count -1; i >= 0; i--) {
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_filename.Text + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
string selectCmd = "Select SUM(Total) As Total_SUM From [" + list_sheetnames.Items[i] + "$]";
using(OleDbConnection excelConn = new OleDbConnection(connString)) {
excelConn.Open();
OleDbCommand command = new OleDbCommand(selectCmd, excelConn);
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable sheetInfo = new DataTable();
da.Fill(sheetInfo);
//Do something with the data.
//list_total.Items.Add(sheetInfo);
list_total.DataSource = da.ToString();
}
}
}
我收到了错误
答案 0 :(得分:0)
看起来您正在尝试将数据表绑定到List。我猜List_total是List<string>
?如果要添加数据表中的值,则需要循环遍历行和项目以获得所需内容。
foreach (var row in da.Rows)
{
foreach (var item in row.ItemArray)
{
//do your checks on the data here and add it to your list if necessary.
list_total.Add(item.ToString());
}
}
您还可以尝试传统的for循环:
for (int i = 0; i < da.Rows.Count; i++)
{
list_total.Add(da.Rows[i]["Total_SUM"].ToString());
}
<强> 更新 强>
所以你的代码现在是:
List<string> lst = new List<string>();
foreach (DataRow r in sheetInfo.Rows)
{
string sheettotal = (string)r["Total_SUM"].ToString();
lst.Add(sheettotal);
}
list_total.DataSource = lst;