title: How to export data table with proper formatting and write text in Excel using C# Microsoft.Office.Interop.Excel?
body: <p>I'm using this function to export a data table into excel.</p>
  
  <pre><code>  protected void ExportExcel(System.Data.DataTable dt) 
      { 
           if (dt == null||dt.Rows.Count==0) return; 
           Microsoft.Office.Interop.Excel.Application xlApp = 
  new Microsoft.Office.Interop.Excel.Application(); 
  
   if (xlApp == null) 
   { 
       return; 
   } 
   System.Globalization.CultureInfo CurrentCI = 
  System.Threading.Thread.CurrentThread.CurrentCulture; 
   System.Threading.Thread.CurrentThread.CurrentCulture = 
      new System.Globalization.CultureInfo("en-US"); 
   Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; 
   Microsoft.Office.Interop.Excel.Workbook workbook = 
   workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); 
   Microsoft.Office.Interop.Excel.Worksheet worksheet = 
  (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; 
   Microsoft.Office.Interop.Excel.Range range; 
   long totalCount = dt.Rows.Count; 
   long rowRead = 0; 
   float percent = 0; 
   for (int i = 0; i &lt; dt.Columns.Count; i++) 
   { 
       worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName; 
       range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; 
       range.Interior.ColorIndex = 15; 
       range.Font.Bold = true; 
  
   } 
  
   for (int r = 0; r &lt; dt.Rows.Count; r++) 
   { 
       for (int i = 0; i &lt; dt.Columns.Count; i++) 
       { 
           worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString(); 
       } 
       rowRead++; 
       percent = ((float)(100 * rowRead)) / totalCount; 
   }
  
   xlApp.Visible = true;
  }
  </code></pre>
  
  <p><img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-ash3/150353_4639369860756_1308281871_n.jpg" alt="RESULT iMAGE"></p>
  
  <p>As you can see in the resulting excel image, the columns are not properly formatted i.e., the column sizes do not adapt to the databound items. How will I make the excel cells auto-adjust according to the data table?</p>
  
  <p>And I also would like to add some text, maybe a header, for say maybe "System.DateTime.Now" or "data table name". How do i do this?</p>