Refer the Eggheadcafe's past post of it and Article
Or
Refer this code
public void ExportToExcel()
{
Microsoft.Office.Interop.Excel.ApplicationClass excel = new ApplicationClass();
excel.Visible = true;
Workbook wBook = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet wSheet = (Worksheet)wBook.Worksheets[1];
Range wRange;
excel.Cells[2, 3] = "Schedule of Professional Tax";
wRange = (Range)excel.Cells[2, 3];
wRange.Font.Bold = true;
excel.Cells[2,4] = "Month/Year:";
wRange = (Range)excel.Cells[2, 4];
wRange.Font.Bold = true;
wRange.Columns.AutoFit();
excel.Cells[2, 5] = dtpMonthYear.Text.ToString();
if (cmbGrade.Text.Trim() != "")
{
excel.Cells[3, 4] = "Grade:";
excel.Cells[3, 5] = cmbGrade.Text.Trim();
}
//Export Column Names
excel.Cells[4, 1] = "S.No";
wRange = (Range)excel.Cells[4, 1];
wRange.Columns.Font.Bold = true;
wRange.Columns.AutoFit();
excel.Cells[4, 2] = "Emp.Code";
wRange = (Range)excel.Cells[4, 2];
wRange.Columns.Font.Bold = true;
wRange.Columns.AutoFit();
excel.Cells[4, 3] = "Name/Designation of person";
wRange = (Range)excel.Cells[4, 3];
wRange.Columns.Font.Bold = true;
wRange.Columns.AutoFit();
excel.Cells[4, 4] = "Amount";
wRange = (Range)excel.Cells[4, 4];
wRange.Columns.Font.Bold = true;
//Add Values
double TotalAmt = 0;
for (int i = 0; i < dgvPTDetails.Rows.Count; i++)
{
excel.Cells[6 + i, 1] = i + 1;
excel.Cells[6 + i, 2] = dgvPTDetails.Rows[i].Cells[1].Value.ToString();
excel.Cells[6 + i, 3] = dgvPTDetails.Rows[i].Cells[2].Value.ToString() + "/" + dgvPTDetails.Rows[i].Cells[3].Value.ToString();
excel.Cells[6 + i, 4] = dgvPTDetails.Rows[i].Cells[4].Value.ToString();
//Calculate TotalAmount
string Amt = "";
Amt = dgvPTDetails.Rows[i].Cells[4].Value.ToString();
if (Amt == "")
{ Amt = "0"; }
TotalAmt = TotalAmt + Convert.ToDouble(Amt);
}
//Display Total
int RowTot = dgvPTDetails.Rows.Count + 7;
excel.Cells[RowTot, 2] = "Total : ";
wRange = (Range)excel.Cells[RowTot, 2];
wRange.Font.Bold = true;
excel.Cells[RowTot, 4] = TotalAmt.ToString();
wRange = (Range)excel.Cells[RowTot, 4];
wRange.Font.Bold = true;
}
Also See those links :
http://www.eggheadcafe.com/community/aspnet/2/42640/autofit-column.aspx
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_23505519.html
http://www.c-sharpcorner.com/UploadFile/mgold/Query2Excel12032005011029AM/Query2Excel.aspx
see that article also:
http://www.eggheadcafe.com/forumpost.aspx?topicid=2&forumpostid=3954