从VB填充的excel数据单元中删除前导0

时间:2015-07-25 13:02:13

标签: c# vb.net excel

在我的vb Windows应用程序中,我使用此代码创建excel报告:

Public Sub CreateExcelFile(ByVal InputDataTable As DataTable, ByVal FileName As String)

    Dim ExcelApp As New Microsoft.Office.Interop.Excel.ApplicationClass
    Dim ExcelWorkbook As Microsoft.Office.Interop.Excel.Workbook = Nothing
    Dim ExcelWorkSheet As Microsoft.Office.Interop.Excel.Worksheet = Nothing
    Dim ColumnIndex As Integer = 0
    Dim RowIndex As Integer = 1
    Try
        ExcelWorkbook = ExcelApp.Workbooks.Add()
        ExcelWorkSheet = ExcelWorkbook.ActiveSheet()
        For Each c As DataColumn In InputDataTable.Columns
            ColumnIndex += 1
            ExcelApp.Cells(RowIndex, ColumnIndex) = c.ColumnName
        Next
        For Each r As DataRow In InputDataTable.Rows
            RowIndex += 1
            ColumnIndex = 0
            For Each c As DataColumn In InputDataTable.Columns
                ColumnIndex += 1
                ExcelApp.Cells(RowIndex, ColumnIndex) = r(c.ColumnName).ToString
            Next
        Next
        ExcelWorkSheet.Columns.AutoFit()
        ExcelWorkbook.SaveAs(FileName)
        ExcelWorkbook.Close()
        ExcelApp.Quit()

    Catch ex As Exception
        MsgBox("Err", MsgBoxStyle.Information + MsgBoxStyle.MsgBoxRtlReading)
    Finally
        ExcelApp = Nothing
        ExcelWorkbook = Nothing
        ExcelWorkSheet = Nothing
        ColumnIndex = Nothing
        RowIndex = Nothing

    End Try
End Sub

如果我的代码或电话号码的第一个字符为0,则不会显示在excel文件中。我使用此代码来解决问题:

 ExcelWorkSheet.Activate()

      ExcelWorkSheet.Cells().Columns.NumberFormat = "@"
      ExcelWorkSheet.Cells().EntireColumn.NumberFormat = "@"

但它不起作用。我读了这个问题,但无法解决我的问题:

Format an Excel column (or cell) as Text in C#?

Set data type like number, text and date in excel column using Microsoft.Office.Interop.Excel in c#

Insert DataTable into Excel Using Microsoft Access Database Engine via OleDb

1 个答案:

答案 0 :(得分:1)

在其中包含数据后设置单元格的格式并不总是有效,因为在转换为原始数据格式时,某些数据可能在输入时丢失。确保首先设置单元格的格式,以便不会截断任何前导零。