在数据库中插入空的Excel单元格作为空白单元格

我有一个简单的button事件导入到数据库中的Excel表。 代码片/部分是这样的..

private void button6_Click(object sender, EventArgs e) { OpenFileDialog theDialog = new OpenFileDialog(); theDialog.Title = "Open Text File"; theDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.xltm;*.xltx"; theDialog.InitialDirectory = @"C:\"; if (theDialog.ShowDialog() == DialogResult.OK) { try { foreach (var worksheetx in Workbook.Worksheets(theDialog.FileName.ToString())) { foreach (var row in worksheetx.Rows) { String Temp = @"INSERT INTO [dbo].[myTable] ([Status] ,[NName] ,[Notes] ) VALUES ('<Status>' ,'<NName>' ,'<Notes>' )"; String Temp1 = Temp; bool ForceContinue = false; foreach (var cell in row.Cells) { if (cell != null) { if (cell.ColumnIndex == 0)Temp1 = Temp1.Replace("<Status>", cell.Text); if (cell.ColumnIndex == 1)Temp1 = Temp1.Replace("<NName>", cell.Text); if (cell.ColumnIndex == 2)Temp1 = Temp1.Replace("<Notes>", cell.Text); } else { //Looking for this part- How to insert 'NULL' or Blank cell.Text } } DBConn.Execute(Temp1); 

例如,如果我的Excel表单列 – “注释”是

 | Check | | | | | 

它目前插入数据库像

 | Check | |<Notes>| |<Notes>| 

我希望它是这样的空白插入为空白

 | Check | | | | | 

尝试将?:运算符与DBNull而不是if语句组合起来。

 foreach (var cell in row.Cells) { if (cell.ColumnIndex == 0) Temp1 = Temp1.Replace("<Status>", string.IsNullOrWhiteSpace(cell.Text) ? DBNull.Value : cell.Text); if (cell.ColumnIndex == 1) Temp1 = Temp1.Replace("<NName>", string.IsNullOrWhiteSpace(cell.Text) ? DBNull.Value : cell.Text); if (cell.ColumnIndex == 2) Temp1 = Temp1.Replace("<Notes>", string.IsNullOrWhiteSpace(cell.Text) ? DBNull.Value : cell.Text); } 

更多阅读这里有一些链接。 ?:和DBNull

replace内部'foreach(var cell in row.Cells)'中的代码块,并用下面的代码replace它。

if (cell != null) { if (cell.ColumnIndex == 0)Temp1 = Temp1.Replace("<Status>", cell.Text); if (cell.ColumnIndex == 1)Temp1 = Temp1.Replace("<NName>", cell.Text); if (cell.ColumnIndex == 2)Temp1 = Temp1.Replace("<Notes>", cell.Text); } else { Temp1 = "" ; }

第一个问题是你没有任何逻辑来捕获一个“空白”的Excel单元格 – 你只需要捕获一个非空单元格的代码。

其次,这个代码中的单元格永远不会为null,因为你只是在你的foreach循环中将它实例化为一个对象。 但是,Value,Value2或Text属性可能为空白或空白。 检查适当的属性为空。

根据你正在尝试做什么,使用这个检查:

 if (cell.Value != null) 

要么

 if (String.IsNullOrEmpty(cell.Text)) 

,但我不认为你甚至需要检查,因为你的replace方法自动执行。

第三,也许我有一个不同的Excel互操作语言,但这甚至不为我编译:

 if (cell.ColumnIndex == 0) 

我能够使用:

 if (cell.Column == 0) 

但是这引发了一个exception,因为Excel数字以1开头,而不是0。

第四,每行都有很长的foreach循环。 试试这个减less处理时间:

 foreach (Range row in sheet.UsedRange) 

第五,你不需要每次都实例化stringTemp。 在第一个循环之前移动该代码。

最后,我只是用这个代码来replace适当的文本:

  foreach (Range cell in row.Cells) { if (cell.Column == 1) Temp1 = Temp1.Replace("<Status>", cell.Text); if (cell.Column == 2) Temp1 = Temp1.Replace("<NName>", cell.Text); if (cell.Column == 3) Temp1 = Temp1.Replace("<Notes>", cell.Text); }