Link to home
Start Free TrialLog in
Avatar of searchsanjaysharma
searchsanjaysharma

asked on

How to lock or password protect the excel file where data has been exported to excel

I am exporting the data from gridview to excel by the following code


Dim Excel As Object = CreateObject("Excel.Application")
        If Excel Is Nothing Then
            MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical)
            Return
        End If
        'Make Excel visible
        Excel.Visible = True
        'Initialize Excel Sheet
        With Excel
            .SheetsInNewWorkbook = 1
            .Workbooks.Add()
            .Worksheets(1).Select()
            'Add header row to Excel Sheet by copying column headers from the Datagrid
            Dim Col As DataGridViewColumn
            Dim i As Integer = 1
            For Each Col In DataGridView1.Columns
                .Cells(1, i).Value = Col.HeaderText
                i += 1
            Next
            'Add data to excel sheet by looping through the rows
            'in the datagrid
            i = 2
            Dim RowItem As DataGridViewRow
            Dim Cell As DataGridViewCell
            For Each RowItem In DataGridView1.Rows
                Dim j As Integer = 1
                For Each Cell In RowItem.Cells
                    .Cells(i, j).Value = Cell.Value
                    j += 1
                Next
                i += 1
            Next
        End With
        Excel.Quit()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
        Excel = Nothing
        MsgBox("Export to Excel Complete", MsgBoxStyle.Information)


How to save this excel file and how to protect it
ASKER CERTIFIED SOLUTION
Avatar of Peter Kiprop
Peter Kiprop
Flag of Kenya image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Joe Howard
Add the code mentioned by Pthepebble before the Excel.Quit() line.
Avatar of searchsanjaysharma
searchsanjaysharma

ASKER

TX