[英]How to change number format in excel sheet through VB.net?
我有一個程序可以將DataGrid
轉換為Excel工作表。 但是現在我的問題是,如果我的數據在Datagrid
為“ 763040059412”,則在我的Excel工作表中進行轉換后,它顯示為“ 7.6304E + 11”。 我不知道該怎么辦。請幫助我。 感謝您
使用Excel自動設置范圍的NumberFormat,如下所示,其中我正在使用您顯示的值。 如果我不使用設置NumberFormat插入該值,則結果與您獲得的結果相同,但是使用NumberFormat時,數字格式正確。
在這里,我正在使用可執行文件文件夾中的Excel文件,您將進行調整以指向您現有的或新創建的Excel文件。
Dim FileName As String = IO.Path.Combine(Application.StartupPath, "Formatting.xlsx")
Dim value As Long = 763040059412
OpenExcelDoFormat(FileName, "", "Sheet1", "G2", 763040059412)
支持通過process.start打開文件的代碼以立即查看結果。 請注意,參數SaveFileName在這里沒有任何意義,因為我對另一個問題進行了調整。
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module OpenWorkSheets4
Public Sub OpenExcelDoFormat(
ByVal OpenFileName As String,
ByVal SaveFileName As String,
ByVal SheetName As String,
ByVal CellAddress As String,
ByVal NewCellValue As Long)
If IO.File.Exists(OpenFileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim xlCells As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(OpenFileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
xlCells = xlWorkSheet.Range(CellAddress)
xlCells.Select()
xlCells.NumberFormat = "0"
xlCells.Value = NewCellValue.ToString
Dim xlColumns As Excel.Range = Nothing
xlColumns = xlCells.EntireColumn
xlColumns.AutoFit()
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlColumns)
xlColumns = Nothing
Else
MessageBox.Show(SheetName & " not found.")
End If
xlWorkSheet.SaveAs(OpenFileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlCells)
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
Process.Start(OpenFileName)
Else
MessageBox.Show("'" & OpenFileName & "' not located. Try one of the write examples first.")
End If
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
End If
obj = Nothing
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module
轉到單元格或范圍級別,並應用NumerFormat = "#,##0.00"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.