Finally I found code:
protected void Page_Load(object sender, EventArgs e)
{
DataSetToExcel(GetDataSet(), false);
}
private static DataSet GetDataSet()
{
DataSet ds = new DataSet();
System.Data.DataTable dt = new System.Data.DataTable("Table");
dt.Columns.Add("Name", Type.GetType("System.String"));
dt.Columns.Add("Address", Type.GetType("System.String"));
dt.Columns.Add("Phone", Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr["Name"] = "Balaji Selvarajan";
dr["Address"] = "Reddiyur";
dr["Phone"] = "000-000-0000";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "Balaji S";
dr["Address"] = "Kattumannar Koil";
dr["Phone"] = "000-000-0000";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
return ds;
}
private static void DataSetToExcel(DataSet ds, Boolean generateIdentity)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
for (int k = 0; k < ds.Tables.Count; k++)
{
System.Data.DataTable dt = ds.Tables[k];
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Add(Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
ws.Name = dt.TableName;
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (i == 0)
ws.Cells[1, j + 1] = dt.Columns[j].ColumnName;
ws.Cells[i + 2, j + 1] = (j == 0 && generateIdentity) ?
(i + 1).ToString() : dt.Rows[i][j].ToString();
}
}
ws.Protect("1", true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
}
wb.Protect("my", true, true);
wb.Password = "Test";
wb.Close();
xlApp.Visible = true;
}