gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:58:54 25 4
gpt4 key购买 nike

之前,我试图将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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com