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

以前,我试图将gridview值导出到excel中。 但与下面给出的代码我能够导出数据到Excel中。 但是仍然无法自动将Excel文件保存C:/驱动器中固定文件夹中 。 下面给出了我写出来导出为ex​​cel的代码。

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...) 

请参阅这里了解更多信息。

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

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

我刚刚使用:

  Dim oexcel As Object Dim obook As Object Dim owrite As New Microsoft.Office.Interop.Excel.Worksheet < your code > owrite.SaveAs("c:\" & foldername) 

这是一个老问题,但也许这会帮助别人。 我最近需要阅读,parsing和写入xlsx文件。 为此,我使用了C#的OpenXML SDK。 MSDN提供了一些关于如何做到这一点的很好的教程。 如果有人有问题,我可以提供我的代码。 只是最后一个注释…当我“发布”的应用程序在客户端的计算机上安装的SDK似乎是必需的。