在导出到Excel(从MS Access)到vb.net期间,将TRUE FALSE转换为1和0

当试图通过VB.NET将我的表从Access导出到Excel时,我希望TRUE和FALSE值在我的Excel表单中显示为1和0。 下面是我的代码,导出和写入Excel中的数据。

If(.Cells(d, e).value = True, 1, 0)抛出一个错误:“ conversion from type string to Boolean is not validconversion from type string to Boolean is not valid ”。 我猜这是因为我的“string”数据以及我的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 

正如@varocarbas在你的问题下面的评论中所提到的,你将意识到你的代码中的错误是什么。

IIf(.Cells(d,e).value = True,1,0)行假定Cell值是布尔types,但情况并非如此(Excel单元总是String)。 避免此问题的方法是将单元格视为string(IIf(.Cells(d,e).value.ToString()。ToLower()=“true”,1,0))或将单元格转换为布尔型(通过Convert.ToBoolean

但是,不要在循环中replace它,而要在“一个GO”的循环之外进行。

在VB.NET 2010 + EXCEL 2010(叹息)中尝试和testing

  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