title: VB.net exporting datagridview to Excel
body: <p>I have a DataGridView and a button that exports the values of the DataGridView to excel. The question is how can I set the values to non editable or read only when it is sent to the excel? And what is the code to set the default cell sizes of the value where it will be displayed?</p>
  
  <p>Here is my code of the Button:</p>
  
  <pre><code> Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Dim App_xls As Object
      Dim Lig_cpt, Col_cpt As Integer
      App_xls = CreateObject("Excel.Application")
      App_xls.workbooks.add()
  
      App_xls.visible = True
  
      Try
  
          For Col_cpt = 0 To DataGridView1.ColumnCount - 1
              App_xls.ActiveSheet.cells(1, Col_cpt + 1).value = DataGridView1.Columns(Col_cpt).HeaderText
          Next
          For Lig_cpt = 0 To DataGridView1.Rows.Count - 1
              For Col_cpt = 0 To DataGridView1.ColumnCount - 1
                  If IsNumeric(DataGridView1.Item(Col_cpt, Lig_cpt).Value) Then
                      App_xls.ActiveSheet.cells(Lig_cpt + 2, Col_cpt + 1).value = CDbl(DataGridView1.Item(Col_cpt, Lig_cpt).Value)
                  Else
                      App_xls.ActiveSheet.cells(Lig_cpt + 2, Col_cpt + 1).value = DataGridView1.Item(Col_cpt, Lig_cpt).Value
  
                  End If
              Next
          Next
  
      Catch ex As Exception
  
      End Try
  
  
  End Sub
  </code></pre>
  
  <p>`</p>