james james

james james

  • NA
  • 419
  • 28.7k

c# export to excel with a Specific sheet name

Nov 29 2017 2:30 PM
The below code when exporting to excel gives the sheet name Book1. How can i edit it to where export the sheet name as "Sams Report"?
 
  1. private void btn_Export_Click(object sender, EventArgs e)  
  2.        {  
  3.            if (dataGridView1.Rows.Count > 0)  
  4.            {  
  5.                Microsoft.Office.Interop.Excel.ApplicationClass XcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();  
  6.                XcelApp.Application.Workbooks.Add(Type.Missing);  
  7.   
  8.                // Storing header part in Excel     
  9.                for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)  
  10.                {  
  11.                    XcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;  
  12.                }  
  13.   
  14.                // Storing Each row and column value to excel sheet     
  15.                for (int i = 0; i < dataGridView1.Rows.Count; i++)  
  16.                {  
  17.                    for (int j = 0; j < dataGridView1.Columns.Count; j++)  
  18.                    {  
  19.                        XcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();  
  20.                    }  
  21.                }  
  22.                XcelApp.Columns.AutoFit();  
  23.                XcelApp.Visible = true;  
  24.            }  
  25.        }  
 
 
 

Answers (9)