Sunday, 3 March 2013

How to Export data to excel (.csv) along with hyperlinks:

List<ListofData> AllData  = ManagerClass.GetAllData();
In the above call you will get data then the exporting them as follows :



 public ActionResult ExportData()
        {


StringWriter stringwrite = new StringWriter();
            stringwrite.WriteLine("title1,title2,title3");
            string style = @"<style> .text { mso-number-format:\@; } </style> ";              
foreach (var item in AllData  )
            {
string value = "=HYPERLINK(\"\"" + RootPath + "\"\"" + ",\"" + "\"" + item.ArticleTitle + "\"\")";
                var append = value.Contains(",")
                              ? string.Format("{0}", value)
                            : value;

 stringwrite.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"", append, item.item1, item.item2));
}
Response.AddHeader("Content-Disposition", "attachment; filename=DataFile.csv");
            Response.ContentType = "application/ms-excel";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            HtmlTextWriter htw = new HtmlTextWriter(stringwrite);
            Response.Write(stringwrite.ToString());
            Response.Write(style);
            Response.End();
            return View();

}


In the above the tag called "style" which is added so that helps you for the hyperlink style export actually the syntax for hyperlink in .csv is : " =HYPERLINK("URL Link","Display Message") "  but the comma is making problem to with us for ".csv" 'comma separated value'  so, use this above method for this problem who were facing.

1 comment: