Tuesday, March 13, 2012

Export Data in CSV or Excel In Apex Salesforce

Hello guys ,
This articles lets you know how to export data in csv or excel.

See Example Below .
Copy paste code according to your data structure.

For Excel :
Note : Make sure if you are on MAC then do not use pageBlock and pageBlockTable other wise you get an issue with extra content on visualforce page like if(!window.sfdcPage){ window.sfdcPage = new ApexPage(); }
So to avoid this issue just use DataTable instead of pageBlock and PageBlockTable.

<apex:page controller="exportExcel" action="{!exportToExcel}" readOnly="true" contentType="application/vnd.ms-excel#ConsignmentSearchData.xls">

    
    <apex:pageBlock >
        <apex:pageBlockTable value="{!lstwrapper}" var="x">
           <apex:column headerValue="shipTo">
                {!x.shipTo}
            </apex:column>
             <apex:column headerValue="searchNumber">
                {!x.searchNumber}
            </apex:column>
             <apex:column headerValue="accountName">
                {!x.accountName}
            </apex:column>
             <apex:column headerValue="businessUnit">
                {!x.businessUnit}
            </apex:column>
             <apex:column headerValue="dateval">
                {!x.dateval}
            </apex:column>
            <apex:column headerValue="expirationDate">
                {!x.expirationDate}
            </apex:column>
             <apex:column headerValue="expirationEndDate">
                {!x.expirationEndDate}
            </apex:column>
            <apex:column headerValue="expirationStartDate">
                {!x.expirationStartDate}
            </apex:column>
             <apex:column headerValue="groupval">
                {!x.groupval}
            </apex:column>
             <apex:column headerValue="implantDate ">
               {!x.implantDate}
            </apex:column>
             <apex:column headerValue="invoiceDate">
                {!x.invoiceDate}
            </apex:column>
             <apex:column headerValue="invoiceNumber">
                {!x.invoiceNumber}
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>   

</apex:page>

For CSV :
<apex:page controller="exportExcel" action="{!exportToExcel}" readOnly="true" contentType="application/vnd.ms-excel#ConsignmentSearchData.csv">{!header}
  <apex:repeat value="{!lstwrapper}" var="x">
       {!x.shipTo},{!x.searchNumber},{!x.accountName},{!x.businessUnit},{!x.dateval},{!x.expirationDate},{!x.expirationEndDate},{!x.expirationStartDate},{!x.groupval},{!x.implantDate},{!x.invoiceDate},{!x.invoiceNumber}
  </apex:repeat>
</apex:page>
Class Code :

public class exportExcel {
  
    public string header{get;set;}
    public List<wrapper> lstwrapper {get; set;}
    public class wrapper{
        public string shipTo {get; set;}
        public string searchNumber{get; set;}
        public string accountName{get; set;}
        public string businessUnit{get; set;}
        public string dateval{get; set;}


        public string expirationDate{get; set;}
        public string expirationEndDate{get; set;}
        public string expirationStartDate{get; set;}
        public string groupval{get; set;}
        public string implantDate {get; set;}
        public string invoiceDate{get; set;}
        public string invoiceNumber{get; set;}         
    }
  
    public string Filetype{get;set;}
    public boolean isExcel {get;set;}
    public boolean isCsv {get;set;}   
  




    public exportExcel(){
            Filetype = '';
            lstwrapper = new List<wrapper>();
            header = 'Ship To,Search Number,Account Name,Business Unit,Date,Expiration Date,Expiration End Date,Expiration Start Date,Group,Implant Date ,Invoice Date,Invoice Number\r\n';                     
    }

  
    public void exportToExcel(){
          string queryString = 'Select c.Account_Name__c, c.Business_Unit__c, c.Date__c, c.Expiration_Date__c,c.Expiration_End_Date__c, c.Expiration_Start_Date__c, c.Group__c, c.Id, c.Implant_Date__c, c.Invoice_Date__c, c.Invoice_Number__c, c.Location__c, c.Name, c.Order_Number__c, c.OwnerId, c.Physician_ID__c, c.PO_Number__c, c.Product_Group__c, c.Product_ID__c, c.Search_ID__c, c.Serial_Number__c, c.Ship_To__c, c.Type__c, c.User_ID__c, c.User_Name__c from Consignment_Search_Data__c c where User_ID__c=\''+UserInfo.getUserId()+'\''; 
          List<Consignment_Search_Data__c> lstConsignmentSearchData = DataBase.Query(queryString);
          system.debug('lstConsignmentSearchData :'+lstConsignmentSearchData.size());
          if(lstConsignmentSearchData.size()>0){
              for(Consignment_Search_Data__c csd :lstConsignmentSearchData){
                  wrapper w = new wrapper();
                  w.shipTo = csd.Ship_To__c ;
                  w.searchNumber = csd.Search_ID__c;
                  w.accountName = csd.Account_Name__c;
                  w.businessUnit = csd.Business_Unit__c ;
                  w.dateval = string.valueof(csd.Date__c);
                  w.expirationDate = string.valueOf(csd.Expiration_Date__c);
                  w.expirationEndDate = string.valueOf(csd.Expiration_End_Date__c);
                  w.expirationStartDate = string.valueOf(csd.Expiration_Start_Date__c);
                  w.groupval = csd.Group__c;
                  w.implantDate = string.valueOf(csd.Implant_Date__c);
                  w.invoiceDate = string.valueOf(csd.Invoice_Date__c) ;
                  w.invoiceNumber = string.valueOf(csd.Invoice_Number__c);
                  lstwrapper.add(w);               
              }             
          }
          system.debug('lstwrapper :'+lstwrapper.size());
    }

  

}


Note : Using the same class code for both page :

16 comments:

  1. Para que a Classe funcione perfeitamente em CSV é necessário adicionar \r\n no ultimo campo, caso não seja incluída essa TAG o documento ficará com uma única linha.

    ReplyDelete
  2. Hello Vijay,

    This has been really helpful. But I would like to export the data into .csv format using a demiliter other than "," (comma). Can you tell me where exactly I should make a change?

    ReplyDelete
    Replies
    1. Hi Prathamesh, Did you find any solution how change the delimeter from Comma to something else? I have comma in my data and cannot use it as delimeter

      Delete
    2. I would think that you would just change the commas between the fields in the CSV code to some other character.

      Delete
    3. I was wrong about that.

      Delete
  3. I checked this in MAC and I didn't get any issue as you had mentioned.. Has the issue been solved with any latest release?

    ReplyDelete
    Replies
    1. Hi Suresh,

      I am not sure about this but I had faced the issue one year ago. Its well n good if you have done your job without any issue.

      Delete
    2. Thanks for you Response Vijay. I had done csv export before but haven't tried for excel. I wasn't sure how to do it for excel. Your sample code worked for me in both Windows and Mac. So,just wanted to know whether you are aware of the fact that the issue in not happening with Mac anymore. Anyway thanks again for the tip.

      Cheers,
      Suresh

      Delete
  4. Thanks, you saved me some time and thinking
    Cheers / Niklas

    ReplyDelete
  5. Very good and easy to implement! You don't happen to have the test class?

    ReplyDelete
  6. Im exporting Data in a excel format. All works well other than trying to get a new line within a field in Excel (2013). I have a Long Text Area field values, I get Test1 Test2 in the cell when I need
    Test1
    Test2 in a single cell

    Please help me on this issue

    ReplyDelete
  7. For more than 10000 records how can we download in excel. 10,000 limit on PageBlocktable.

    ReplyDelete
  8. I need to split export to excel file into multiple sheet. how do i need to do this coding ?

    ReplyDelete
    Replies
    1. I know it was long back even though i wanted ask
      Have found Any solution

      Delete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hi! i have problem with export data in excel from a visualforce page with windows 10. do Do exist any
    Difference with windows 10?

    ReplyDelete