C# 导出到Excel(DBNull错误)
我试图根据组合框中的类别将数据导出到单独的电子表格中。 组合框有一个数据表作为数据源。此数据表有两列:categoryid(ValueMember)和Category(DisplayMember) 问题是,我得到一个错误: “无法将对象从dbnull强制转换为其他类型。” 但是,my DataTable是从数据库生成的,categoryid和Category都不能为空 这是我的密码:C# 导出到Excel(DBNull错误),c#,database,excel,winforms,combobox,C#,Database,Excel,Winforms,Combobox,我试图根据组合框中的类别将数据导出到单独的电子表格中。 组合框有一个数据表作为数据源。此数据表有两列:categoryid(ValueMember)和Category(DisplayMember) 问题是,我得到一个错误: “无法将对象从dbnull强制转换为其他类型。” 但是,my DataTable是从数据库生成的,categoryid和Category都不能为空 这是我的密码: private void excelSpreadsheetToolStripMenuItem_Click(obj
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());
}
尝试这样做:
if(dvrow.Row["categoryid"] != DBNull.Value){
xwb.Worksheets.Add(exceldt(Convert.ToInt32(dvrow.Row["categoryid"])), dvrow.Row["Category"].ToString());
}
....
using (var sqlcmd = new SqlCommand("SELECT Item, Quantity, Date FROM inventory_table WHERE categoryid= @catid")){
...
sqlcmd.Parameters.Add(new SqlParameter("catid", id));
....
}
并移动xwb.SaveAs(fname)代码>离开foreach,效率更高
和@Max say在查询中使用如下参数:
if(dvrow.Row["categoryid"] != DBNull.Value){
xwb.Worksheets.Add(exceldt(Convert.ToInt32(dvrow.Row["categoryid"])), dvrow.Row["Category"].ToString());
}
....
using (var sqlcmd = new SqlCommand("SELECT Item, Quantity, Date FROM inventory_table WHERE categoryid= @catid")){
...
sqlcmd.Parameters.Add(new SqlParameter("catid", id));
....
}
请考虑使用Sql参数<代码>使用(var SQL LCMD=新的Sql命令(“选择项目,数量,从SooDyyyLoad中的日期,在CythyID=+i”)< /代码>这条线是脆弱的。为什么你不改变你的查询还添加一个<代码>和到WHERE子句,在那里你撤回不是空的数据。请记住,Null和Empty
不是一回事@John@MethodMan注意。但是,我的数据库中的categoryid列不能为null
;这是一个限制条件。我得到一个错误:运算符“==”不能应用于“System.Data.DataTable”和“System.DBNull”类型的操作数@John我已经更新了代码。。我认为问题来自于dvrow.Row[“categoryid”]
castI没有试图添加“id”。我试图根据另一个表的“categoryid”将数据从数据库中的表拉入DataTable。我已经发布了解决方案的尝试。我最后也犯了同样的错误。我注意到在您的代码中,您说如果“行等于DBNull值,那么添加工作表”。这就是为什么我的if
语句中有“NOT”的原因。@John是的,我有正确的答案,你需要在if中添加NOT=代码>非==