导出到Excel(DBNull错误)

时间:2015-05-05 17:53:31

标签: c# database excel winforms combobox

我正在尝试根据组合框中的类别将数据导出到单独的电子表格中。 组合框具有DataTable作为数据源。此DataTable有两列:categoryid(ValueMember)和Category(DisplayMember)。

问题是,我收到错误:

  

“无法将对象从dbnull强制转换为其他类型。”

但是,我的DataTable是从数据库生成的,categoryid和Category都没有NULLS。

这是我的代码:

private void excelSpreadsheetToolStripMenuItem_Click(object sender, EventArgs e)
{
    try
    {
        string fname = "Inventory Report.xlsx";
        XLWorkbook xwb = new XLWorkbook();
        foreach (DataRowView dvrow in catcombobox.Items)
        {
                //gives integer to function (categoryid), and gives name to spreadsheet (Category)
                xwb.Worksheets.Add(exceldt(Convert.ToInt32(dvrow.Row["categoryid"])), dvrow.Row["Category"].ToString());
                xwb.SaveAs(fname);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private DataTable exceldt(int i)
{
    using (var sqlcmd = new SqlCommand("SELECT Item, Quantity, Date FROM inventory_table WHERE categoryid= " + i))
    {
        using (SqlDataAdapter sqlda = new SqlDataAdapter())
        {
            sqlcmd.Connection = sqlconnection;
            sqlda.SelectCommand = sqlcmd;

            using (DataTable dt = new DataTable())
            {
                sqlda.Fill(dt);
                return dt;
            }
        }
    }
}

我该如何解决这个问题?

尝试解决方案:

                    if (!(dvrow.Row["categoryid"].Equals(DBNull.Value)))
                    {
                        xwb.Worksheets.Add(exceldt(Convert.ToInt32(dvrow.Row["categoryid"])), dvrow.Row["Category"].ToString());
                    }

1 个答案:

答案 0 :(得分:1)

尝试做这样的事情:

if(dvrow.Row["categoryid"] != DBNull.Value){
    xwb.Worksheets.Add(exceldt(Convert.ToInt32(dvrow.Row["categoryid"])), dvrow.Row["Category"].ToString());
}

并将xwb.SaveAs(fname);移出foreach,效率更高。

和@Max说要在查询中使用参数,如下所示:

....
using (var sqlcmd = new SqlCommand("SELECT Item, Quantity, Date FROM inventory_table WHERE categoryid= @catid")){
...
  sqlcmd.Parameters.Add(new SqlParameter("catid", id));
....
}