public void DtToExcel(DataTable table, string filename)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Write(@");
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="+filename+".xls");
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
//sets font
HttpContext.Current.Response.Write("<font style="font-size:10.0pt; font-family:Calibri;">");
HttpContext.Current.Response.Write("<br><br><br>");
//sets the table border, cell spacing, border color, font of the text, background, foreground, font height
HttpContext.Current.Response.Write("<table border="1" bgcolor="#FFFFFF" hold=" /> " bordercolor="#000000" cellspacing="0" cellpadding="0" style="font-size:10.0pt; font-family:Calibri; background:white;"> <tr>");
for (int j = 0; j < table.Columns.Count; j++)
{ //write in new column
HttpContext.Current.Response.Write("<td>");
//Get column headers and make it as bold in excel columns
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.Write(table.Columns[j].ColumnName.ToString());
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.Write("</td>");
}
HttpContext.Current.Response.Write("</tr>");
foreach (DataRow row in table.Rows)
{//write in new row
HttpContext.Current.Response.Write("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
HttpContext.Current.Response.Write("<td>");
HttpContext.Current.Response.Write(row[i].ToString());
HttpContext.Current.Response.Write("</td>");
}
HttpContext.Current.Response.Write("</tr>");
}
HttpContext.Current.Response.Write("</table>");
HttpContext.Current.Response.Write("</br></br></br></font>");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
public DataTable GetTable(string filename, string SheetName, string outTableName)
{
try
{
string Con = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=" + filename + ";" +
@"Extended Properties=" + Convert.ToChar(34).ToString() +
@"Excel 8.0;" + "Imex=2;" + "HDR=Yes;" + Convert.ToChar(34).ToString();
OleDbConnection oleConn = new OleDbConnection(Con);
oleConn.Open();
OleDbCommand oleCmdSelect = new OleDbCommand();
oleCmdSelect = new OleDbCommand(
@"SELECT * FROM ["
+ SheetName
+ "$" + "]", oleConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = oleCmdSelect;
DataTable dt = new DataTable(outTableName);
oleAdapter.FillSchema(dt, SchemaType.Source);
oleAdapter.Fill(dt);
oleCmdSelect.Dispose();
oleCmdSelect = null;
oleAdapter.Dispose();
oleAdapter = null;
oleConn.Dispose();
oleConn = null;
return dt;
}
catch (Exception ex)
{
throw ex;
}
}