在尝试通过VB.NET
将我的表从Access导出到Excel时,我希望TRUE和FALSE值在我的Excel工作表中显示为1s和0。下面是我在excel中导出和写入数据的代码。
If(.Cells(d, e).value = True, 1, 0)
会抛出错误“conversion from type string to Boolean is not valid
”。我想这是因为我在Access表中也有“字符串”数据。有人可以帮忙。
Dim e As Integer = 1
For col = 0 To ComDset2.Tables(0).Columns.Count - 1
d = 2
For row = 0 To ComDset2.Tables(0).Rows.Count - 1
.Cells(d, e).Value = ComDset2.Tables(0).Rows(row).ItemArray(col)
IIf(.Cells(d, e).value = True, 1, 0)
d += 1
Next
e += 1
Next
答案 0 :(得分:3)
如@varocarbas在您的问题下面的评论中所提到的,您将意识到代码中的错误是什么。
IIf(.Cells(d,e).value = True,1,0)行假定Cell值是布尔类型,不是这种情况(Excel单元格总是String)。避免此问题的方法是将单元格视为字符串(IIf(.Cells(d,e).value.ToString()。ToLower()=“true”,1,0))或将单元格转换为布尔值(通过Convert.ToBoolean
但是,不要在循环中替换它,而是在ONE GO中循环外部。
在VB.NET 2010 + EXCEL 2010(叹气)中进行了测试和测试
rng.Replace(What:="TRUE", Replacement:="1", LookAt:=Excel.XlLookAt.xlWhole, _
SearchOrder:=Excel.XlSearchOrder.xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False)
rng.Replace(What:="FALSE", Replacement:="0", LookAt:=Excel.XlLookAt.xlWhole, _
SearchOrder:=Excel.XlSearchOrder.xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False)
更多来自评论的跟进
参见此示例
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'~~> Define your Excel Objects
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlWorkBook = xlApp.Workbooks.Open("C:\Sample.xlsx")
xlWorkSheet = xlWorkBook.Sheets(1)
Dim i As Integer = 1
Dim d As Integer = 0
Dim startRow As Integer = 0
With xlWorkSheet
For col = 0 To ComDset2.Tables(0).Columns.Count - 1
d = 2
startRow = d
For Row = 0 To ComDset2.Tables(0).Rows.Count - 1
.Cells(d, e).Value = ComDset2.Tables(0).Rows(Row).ItemArray(col)
d += 1
Next
'~~> Create your range here
Dim rng As Excel.Range = .Range(.Cells(startRow, i), .Cells(d - 1, i))
rng.Replace(What:="TRUE", Replacement:="1", LookAt:=Excel.XlLookAt.xlWhole, _
SearchOrder:=Excel.XlSearchOrder.xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False)
i += 1
Next
End With
End Sub
End Class