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.Applic ation")
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.InteropServ ices.Marsh al.Release ComObject( Excel)
Excel = Nothing
MsgBox("Export to Excel Complete", MsgBoxStyle.Information)
How to save this excel file and how to protect it
Dim Excel As Object = CreateObject("Excel.Applic
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.InteropServ
Excel = Nothing
MsgBox("Export to Excel Complete", MsgBoxStyle.Information)
How to save this excel file and how to protect it
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Add the code mentioned by Pthepebble before the Excel.Quit() line.
ASKER
TX