+ Start a Discussion
Ragula SivakumarRagula Sivakumar 

CSV file to read using lWC

Hi All,

I am new to developing and give me some insights how to upload csv file using LWC .

Regard,
Siva 
Ragula SivakumarRagula Sivakumar
I have tried belwo code :

HTML
<template>
    <lightning-file-upload 
    
            name="Campaign upload"
            accept={acceptedFormats}
            record-id={myRecordId}
            onuploadfinished={handleUploadFinished}
            single>
    </lightning-file-upload>
</template if:true ={success} >
<c-error-panel errors={success}></c-error-panel>
</template>
<template if:true={failure}>
<c-error-panel errors={failure}></c-error-panel>
</template>
    
</template>



Js:

import { LightningElement,track } from 'lwc';
import insertdata from '@salesforce/apex/importdata.importCSVFile'
export default class Fileupload extends LightningElement {
@track success;
@track failure;
    get acceptedFormats() {
        return ['.csv'];
    }
        handleUploadFinished(event){
            insertdata(){
                .then( result=> {
                    this.success="result";
                    
                })
                .catch(error=>{
                    this.failure=error;

                });
            }
            }
        }



Apex class:
public class importdata{
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<Campaignmember> campaigmemb{get;set;}
  public importdata(){
    csvFileLines = new String[]{};
    campaigmemb= New List<Campaignmember>(); 
  }
  
  public void importCSVFile(){
       
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
            
           for(Integer i=1;i<csvFileLines.size();i++){
               Campaignmember  camobj = new Campaignmember() ;
               string[] csvRecordData = csvFileLines[i].split(',');
               camobj . CampaignId= csvRecordData[0] ;             
               camobj .ContactId= csvRecordData[1];
               camobj .Status= csvRecordData[2];
                                                                                          
               campaigmemb.add(camobj );   
           }
        insert campaigmemb;
        }
        

}
 
Shaik Naga janiShaik Naga jani
Hi Sivakumar,

Once File Uploaded Successfully, File Upload Component returns the File Object. It Contains Files Name and ContentDocumentIds.
I updated your code little bit, test your code and to read CSV file data in apex or javascript check below links.
In javascript
https://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript
In Apex
http://www.saaspie.com/reading-csv-file-in-apex/
HTML Code
==========
<template>
<lightning-file-upload 
		name="Campaign upload"
		accept={acceptedFormats}
		record-id={myRecordId}
		onuploadfinished={handleUploadFinished}
		single>
</lightning-file-upload>
</template if:true ={success} >
<c-error-panel errors={success}></c-error-panel>
</template>
<template if:true={failure}>
<c-error-panel errors={failure}></c-error-panel>
</template>

</template>
Javascript Code
=============
import {LightningElement,track} from 'lwc';
import insertdata from '@salesforce/apex/importdata.readCSVFileInsertMember';

export default class Fileupload extends LightningElement {
	@track success;
	@track failure;
	get acceptedFormats() {
		return ['.csv'];
	}
	handleUploadFinished(event) {
		const uploadedFiles = event.detail.files;
		
		insertdata({idContentDocument : uploadedFiles[0].documentId}) {
		.then(result => {
			this.success = "Campaign Member Inserted Successfully!!";
			
		})
		.catch(error => {
			this.failure = error;
			});
		}
	}
}
Apex Class
=========
public class importdata{
	
	@AuraEnabled
	public void readCSVFileInsertMember(Id idContentDocument){
		if(idContentDocument != null) {
			ContentVersion objVersion = [Select Id, VersionData FROM ContentVersion WHERE ContentDocumentId =: idContentDocument][0];
			
			if(objVersion != null) {
				String csvAsString = Blob.valueOf(VersionData).toString();
		  
				String[] csvFileLines = csvAsString.split('\n'); 
				
				List<Campaignmember> lstCampaignMembers = new List<Campaignmember>();
				
				for(Integer i=1;i<csvFileLines.size();i++){
					Campaignmember  camobj = new Campaignmember() ;
					string[] csvRecordData = csvFileLines[i].split(',');
					camobj.CampaignId= csvRecordData[0] ;             
					camobj.ContactId= csvRecordData[1];
					camobj.Status= csvRecordData[2];
																							   
					lstCampaignMembers.add(camobj );   
				}
				
				if(!lstCampaignMembers.isEmpty()) {
					insert campaigmemb;
				}
			}
			else {
				// return error message to error
			}
		}
   }
}
Kindly mark this as solved if the reply was helpful.
Thanks
Shaik
 
Ragula SivakumarRagula Sivakumar
Hi ,

I am getting error on apex class

Non static AuraEnabled methods must be named with a prefix 'get' at line 4 column 17
Ragula SivakumarRagula Sivakumar
hi @Shaik Naga jani

I am getting error on apex class

Non static AuraEnabled methods must be named with a prefix 'get' at line 4 column 17
Shaik Naga janiShaik Naga jani
Declare method as static it resolves the error.
@AuraEnabled must be static methods.
Ragula SivakumarRagula Sivakumar
Hi @sahik NagaJani ,

I have added static method and  some changes now the Apex class dont have nay error .
 Blob csvFileBody =objVersion.VersionData;
               String csvAsString = csvFileBody.toString();

But coudl not deploy the compoent to org due to error .