DataGridView到Excel - 保存为文本的数字

时间:2016-02-19 14:08:15

标签: vb.net excel datagridview

我有一个VB.Net表单,可以将DataGridView保存为Excel,但它会将数字保存为文本。这意味着饼图和东西不会“刷新”。 我应该用VB代码中的数字格式化列还是有另一种方法将数字保存为数字?

使用Excel模板后,DataGridView值将转到现有文件。我认为它们将按照格式化单元格的方式进行格式化。

这是我正在使用的代码的一部分。

Private Sub ButtonExport_Click(sender As Object, e As EventArgs) Handles ButtonExport.Click
    Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
    Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "template.xlsx")

    Dim misValue As Object = System.Reflection.Missing.Value
    Dim i As Integer
    Dim j As Integer

    xlApp = New Microsoft.Office.Interop.Excel.Application
    xlWorkBook = xlApp.Workbooks.Open(xlPath)
    xlWorkSheet = xlWorkBook.Worksheets("data")

    For i = 0 To DataGridView1.RowCount - 1
        For j = 0 To DataGridView1.ColumnCount - 1
            For k As Integer = 1 To DataGridView1.Columns.Count
                xlWorkSheet.Cells(i + 1, j + 4) = DataGridView1(j, i).Value
            Next
        Next
    Next 
    xlWorkSheet.SaveAs("C:\Users\User\Desktop\" & TextBox3.Text & ".xlsx")
    xlWorkBook.Close()
    xlApp.Quit()

    Me.Close()
    releaseObject(xlApp)
    releaseObject(xlWorkBook)
    releaseObject(xlWorkSheet)
End Sub

我已经尝试了DataGridView1.Columns(2).ValueType = GetType(Decimal),但它什么也没做。

1 个答案:

答案 0 :(得分:0)

OP再次回答:D

For i = 0 To DataGridView2.RowCount - 1
   For j = 0 To DataGridView2.ColumnCount - 1
     Dim val As Object = DataGridView2(2, i).Value
        If IsDBNull(val) Then
            xlWorkSheet.Cells(i + 1, 3) = Nothing
        Else
            xlWorkSheet.Cells(i + 1, 3) = CDbl(val)
      End If
   Next
Next