Author Topic: Force.com visualforce page ExportToCSV is not working  (Read 4175 times)

snehal

  • Pro Economy
  • Newbie
  • *
  • Posts: 1
    • View Profile
Force.com visualforce page ExportToCSV is not working
« on: November 09, 2013, 10:24:49 pm »
I am trying to use the ExporToCSV function in a visualforce page, but the sample code provided in the demo site doesn't work.
I am able to retrieve data but not able to save the exported file.

I tried to explain the issue in the attachment. Any help is much appreciated.

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6309
    • View Profile
Re: Force.com visualforce page ExportToCSV is not working
« Reply #1 on: November 10, 2013, 12:41:40 am »
Snehal

You also need to implement server side code as shown in the demo under ASP.NET and PHP tabs.
http://paramquery.com/pro/demos/export_csv

Server side code consists of two steps / requests:

1) Save the posted contents in a csv file and return file name.
Code: [Select]
[HttpPost, ValidateInput(false)]       
public String excel(String extension, String excel)
{
    if (extension != "csv" && extension != "xml")
    {               
        throw new Exception("Unsupported extension");
    }
    String filename = "pqGrid." + extension;           
    System.IO.File.WriteAllText(Server.MapPath("~") + "\\" + filename, excel);
    return filename;
}

2) Return the file to browser.

Code: [Select]
[HttpGet]
public FileContentResult excel(String filename)
{
    String path = Server.MapPath("~") + "\\" + filename;
    String contents = System.IO.File.ReadAllText(path);
 
    if(filename.EndsWith(".csv")){
        return File(new System.Text.UTF8Encoding().GetBytes(contents), "text/csv", filename);
    }
    else if(filename.EndsWith(".xml")){
        return File(new System.Text.UTF8Encoding().GetBytes(contents), "text/xml", filename);
    }
    else{
        throw new Exception("unknown extension");
    }
}