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

时间:2013-05-14 06:19:44

标签: vb.net excel gridview directory

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

有没有人可以帮我解决一下如何在VB.NET中自动保存excel文件的问题?

3 个答案:

答案 0 :(得分:5)

SaveAs方法是为Excel.Workbook

定义的

Try的最后,在Catch之前,写下:

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

有关更多信息,请参阅here

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

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

答案 1 :(得分:0)

我刚刚使用过:

    Dim oexcel As Object
    Dim obook As Object
    Dim owrite As New Microsoft.Office.Interop.Excel.Worksheet

    < your code > 

   owrite.SaveAs("c:\" & foldername)

答案 2 :(得分:0)

这是一个较老的问题,但也许这会帮助某人。 我最近需要读取,解析和编写xlsx文件。为此,我使用带有C#的OpenXML SDK。 MSDN提供了一些有关如何执行此操作的好教程。 如果有人有疑问,我可以提供我的代码。 最后一个注释......当我“发布”应用程序时,似乎需要在客户端的计算机上安装SDK。