title: How to export datagridview data to excel?
body: <p>my export code</p>
  
  <p>This code writes data in excel but the contents are fitting in to the cells. they are scattered.</p>
  
  <pre><code>   public static void export_to_excel(DataGridView dgv, string excel_file) 
       { 
           int cols; 
           //open file
           StreamWriter wr = new StreamWriter(excel_file); 
           cols = dgv.Columns.Count; 
           for (int i = 0; i &lt; cols; i++)
           {
               wr.Write(dgv.Columns[i].HeaderText.ToString().ToUpper() + "\t");
           }
           wr.WriteLine(); //write rows to excel file 
  
           for (int i = 0; i &lt; (dgv.Rows.Count - 1); i++)
           {
               for (int j = 0; j &lt; cols; j++) 
               { 
                   if (dgv.Rows[i].Cells[j].Value != null) 
                       wr.Write(dgv.Rows[i].Cells[j].Value + "\t");
                   else 
                   { 
                       wr.Write("\t");
                   }
               }
               wr.WriteLine(); 
           } 
           //close file 
           wr.Close(); }
  </code></pre>