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

标签 vb.net excel gridview directory

之前,我试图将gridview值导出到excel中。但通过下面给出的代码,我可以将数据导出到 Excel 中。但仍然无法自动保存该 Excel 文件到 C:/驱动器中的固定文件夹。下面给出了我编写的导出到 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

这里有人可以帮我解决如何在 VB.NET 中自动保存 Excel 文件的问题吗?

最佳答案

SaveAs 方法是为 Excel.Workbook 定义的

Try 结束时,在 Catch 之前,写下:

excelBook.SaveAs(<some path here>, etc...)

引用here了解更多信息。

要正确退出 Excel,请在开头的 Finally block 中写入:

xlApp.Workbooks.Close()
xlApp.Quit()

关于vb.net - 如何在vb.net中保存excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16536372/

相关文章:

excel - 增强 excel 多个查找和替换脚本

Python读取SAS生成的XML类型.xls文件

c# - Gridview 分页在添加页面大小时消失

c# - ASP.NET GridView 有没有一种方法可以根据您所在的单元格获取列名称

Android - 网格中项目之间的 RecyclerView 间距

c# - 此代码的 VB.NET 版本是什么?

vb.net - LINQ 集合中的 Where 语句

JavaScript 将按钮 ID 传递给 asp.net 隐藏字段

c# - 形成两个对象列表联合的最简单方法(包含 Int 和字符串值)

ios - 无法在 UIDocumentInteractionController/UIWebView 中显示 .xlsx 甲酸盐