如何在vb.net中保存excel文件

Sou*_*taP 3 vb.net directory excel gridview

以前,我试图将gridview值导出到excel中.但是使用下面给出的代码,我可以将数据导出到excel中.但仍然无法自动保存 excel文件到C:/ drive中固定文件夹.我写入导出到excel的代码如下.

Private Sub ButtonExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)   Handles ButtonExport.Click
Dim rowsTotal, colsTotal As Short
Dim I, j, iC As Short
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
Dim xlApp As New Excel.Application
Try
    Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
    Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
    xlApp.Visible = True
    rowsTotal = DataGridView1.RowCount - 1
    colsTotal = DataGridView1.Columns.Count - 1
    With excelWorksheet
        .Cells.Select()
        .Cells.Delete()
        For iC = 0 To colsTotal
            .Cells(1, iC + 1).Value = DataGridView1.Columns(iC).HeaderText
        Next
        For I = 0 To rowsTotal - 1
            For j = 0 To colsTotal
                .Cells(I + 2, j + 1).value = DataGrid1.Rows(I).Cells(j).Value
            Next j
        Next I
        .Rows("1:1").Font.FontStyle = "Bold"
        .Rows("1:1").Font.Size = 10
        .Cells.Columns.AutoFit()
        .Cells.Select()
        .Cells.EntireColumn.AutoFit()
        .Cells(1, 1).Select()
    End With
Catch ex As Exception
    MsgBox("Export Excel Error " & ex.Message)
Finally
    'RELEASE ALLOACTED RESOURCES
    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
    xlApp = Nothing
End Try
End Sub
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我解决这个问题,如何在VB.NET中自动保存excel文件?

Adr*_*oix 5

SaveAs方法是为.定义的 Excel.Workbook

在你的结尾Try,就在之前Catch,写下:

excelBook.SaveAs(<some path here>, etc...)
Run Code Online (Sandbox Code Playgroud)

这里指的是更多信息.

要正确退出Excel,请Finally在开头写入块:

xlApp.Workbooks.Close()
xlApp.Quit()
Run Code Online (Sandbox Code Playgroud)

  • 也许只是尝试`excelBook.SaveAs("C:\ excelfile.xlsx")` (2认同)