Export Data into Excel
public static string ExportToExcelFromDataTable(DataTable dtOrig, int[] delColIndx, string[] colNames, string filename)
{
try
{
if (!validateDelColIndx(dtOrig, delColIndx))
{
return "Verify the list of indices to be deleted !";
}
if (colNames.Length > (dtOrig.Columns.Count - delColIndx.Length))
{
return "No of column names didn't match the no of columns that will be available in the final result !";
}
DataTable dtExcel = dtOrig.Copy();
//remove the unwanted columns
int decr = 0;
foreach (int looInt in delColIndx)
{
dtExcel.Columns.RemoveAt(looInt - decr);
decr++;
}
dtExcel.AcceptChanges();
//change column header names as per requirement
int incre = 0;
foreach (string loopStr in colNames)
{
dtExcel.Columns[incre].ColumnName = loopStr;
incre++;
}
dtExcel.AcceptChanges();
string downloadFile = "attachment; filename=" + filename + ".xls";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", downloadFile);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
string nextColumn = "";
foreach (DataColumn col in dtExcel.Columns)
{
HttpContext.Current.Response.Write(nextColumn + col.ColumnName);
nextColumn = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in dtExcel.Rows)
{
nextColumn = "";
for (i = 0; i < dtExcel.Columns.Count; i++)
{
HttpContext.Current.Response.Write(nextColumn + dr[i].ToString());
nextColumn = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
return string.Empty;
}
catch (Exception ex)
{
return ex.Message;
}
}
------------------------------------------------------------------------------------------------------------
protected void btnExport_Click(object sender, EventArgs e)
{
clsDAL obj = new clsDAL();
DataTable dt = new DataTable();
dt = obj.GetDataTable("Ps_Sp_GetStudDataForExport");
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
clsDAL Stud = new clsDAL();
Hashtable htStud = new Hashtable();
htStud.Add("@StudId", dr["StudId"]);
Stud.ExecuteScalar("ps_sp_InsertExpExlData", htStud);
}
ExportToExcelFromDataTable(dt, new int[] { 0 }, new string[] { "AdmnNo", "AdmnDate", "SessionYear", "ReadingClass", "Section", "RollNo", "FullName", "NickName", "DOB", "FatherName", "FatherOccupation", "MotherName", "MotherOccupation", "Gender", "Religion", "Category", "Nationality", "MotherTongue", "PresAddress", "PresAddrDist", "PresAddrPin", "PresAddrPS", "PermAddress", "PermAddrDist", "PermAddrPin", "PermAddrPS", "Phone", "Mobile", "UrbanRuralTribe", "SSVMID" }, "../Reports/Exported_Files/SSVM_StudentDetails" + DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") + ".xls");
}
else
{
lblMsg.Text = "No data exist to export !";
}
}
No comments:
Post a Comment