How to Save excel file in vb.net

老子叫甜甜 提交于 2019-12-13 14:19:28

问题


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

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


回答1:


The SaveAs method is defined for Excel.Workbook

At the end of your Try, just before the Catch, write :

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

Refers to here for more informations.

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

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



回答2:


i just used :

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

    < your code > 

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



回答3:


This is an older question but maybe this'll help someone still. I recently needed to read, parse and write xlsx files. I used the OpenXML SDK with C# for this purpose. MSDN provides some good tutorials on how to do this. If anyone has questions I can provide my code. Just one last note...when I "published" the app an installation of the SDK on the client's computer seemed to be required.



来源:https://stackoverflow.com/questions/16536372/how-to-save-excel-file-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!