如何在vb.net中保存Excel文件 [英] How to Save excel file in vb.net

查看:961
本文介绍了如何在vb.net中保存Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我试图将gridview值导出到excel。但是使用下面给出的代码,我可以将数据导出到excel。但仍无法自动保存该excel文件到假定在C:/驱动器中的固定文件夹中。下面给出了我编写的要导出到excel中的代码。

Previously , I was trying to export gridview value into excel. but with the code given below i am able to export data into excel. but still not able to Save Automatically that excel file into a fixed folder suppose in C:/ drive. The code which i have written to export into excel is given below.

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文件?

can anybody over here please help me out from this problem that how to save that excel file automatically in VB.NET??

推荐答案

SaveAs方法是为定义的Excel.Workbook

The SaveAs method is defined for Excel.Workbook

Try 末尾,就在捕获,写:

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

是指此处以获取更多信息。

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

And to exit properly Excel, write in your Finally block at the start :

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

这篇关于如何在vb.net中保存Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆