Code to print simple data table values to csv.
public ActionResult PrintDataToCsv()
{
string StartDate = Request.Params["StartDateP"] == null ? "" : Request.Params["StartDateP"].ToString();
string EndDate = Request.Params["EndDateP"] == null ? "" : Request.Params["EndDateP"].ToString();
string PageName = Request.Params["PageName"] == null ? "" : Request.Params["PageName"].ToString();
String EnddateConverted = "";
String StardateConverted = "";
if (StartDate != "")
{
StardateConverted = Convert.ToDateTime(StartDate.ToString()).ToString("MM/dd/yyyy");
}
else
{
StardateConverted = StartDate;
}
if (EndDate != "")
{
EnddateConverted = Convert.ToDateTime(EndDate.ToString()).ToString("MM/dd/yyyy");
}
else
{
EnddateConverted = EndDate;
}
System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();
//Here is my datatable which return from procedures.
DataTable dt = GetAllDataToPintToCsv(StardateConverted, EnddateConverted,PageName);
StringWriter sw = new StringWriter();
//Header Part
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i]);
if (i < dt.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
//Header Data
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < dt.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=myfilename.csv");
Response.ContentType = "text/csv";
Response.Charset = "";
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("/account/PrintDataToCsv");
}
<form name="Printing" id="Printing" action="/account/PrintDataToCsv" >
<input type="hidden" id="StartDate" name="StartDateP" value="@StartDate">
<input type="hidden" id="EndDate" name="EndDateP" value="@EndDate">
<input type="hidden" name="PageName" id="searchdata" value="@PageName" />
<button type="submit" class="btn btn-success btn-export" title="Print">Export</button>
</form>
0 comments:
Post a Comment