In Salesforce, data entry can sometimes be time-consuming, especially when dealing with large datasets. However, with the power of Apex and Lightning Web Components (LWC), you can streamline this process by allowing users to upload CSV files directly into your Salesforce org. In this tutorial, we’ll walk through the steps to create an Apex class for processing CSV files and an LWC component for the user interface.
Step 1: Create Apex Class – CsvUploadController
// CsvUploadController.apxc
public with sharing class CsvUploadController {
@AuraEnabled
public static String uploadCsvFile(String base64Data) {
try {
List<Account> accountsToInsert = new List<Account>();
// Decode base64 data
String csvData = EncodingUtil.base64Decode(base64Data).toString();
// Split CSV rows
List<String> csvRows = csvData.split('\n');
// Skip header row if present
Boolean isFirstRow = true;
for (String csvRow : csvRows) {
if (isFirstRow) {
isFirstRow = false;
continue;
}
// Split CSV columns
List<String> csvColumns = csvRow.split(',');
// Create Account record
Account acc = new Account(
Name = csvColumns[0]
// Add other fields as needed
);
accountsToInsert.add(acc);
}
// Insert accounts
if (!accountsToInsert.isEmpty()) {
insert accountsToInsert;
}
return 'Success';
} catch (Exception ex) {
return 'Error: ' + ex.getMessage();
}
}
}
Step 2: Create an LWC Component – csvUpload
csvUpload.html
<template>
<lightning-card title="Upload CSV" icon-name="standard:file">
<lightning-input type="file" label="Choose CSV File" accept=".csv" onchange={handleFileChange}></lightning-input>
<lightning-button label="Upload" onclick={uploadCsv} variant="brand"></lightning-button>
</lightning-card>
</template>
csvUpload.js
// csvUpload.js
import { LightningElement, api } from 'lwc';
import uploadCsvFile from '@salesforce/apex/CsvUploadController.uploadCsvFile';
export default class CsvUpload extends LightningElement {
@api recordId;
csvFile;
handleFileChange(event) {
this.csvFile = event.target.files[0];
}
uploadCsv() {
if (this.csvFile) {
const reader = new FileReader();
reader.onload = (event) => {
const base64Data = btoa(event.target.result);
uploadCsvFile({ base64Data })
.then(result => {
console.log(result);
// Handle success or display a confirmation message
})
.catch(error => {
console.error(error);
// Handle error
});
};
reader.readAsBinaryString(this.csvFile);
}
}
}
Conclusion
by creating an Apex class for CSV file processing and an LWC component for user interaction, Salesforce users can efficiently upload data, saving time and reducing errors. This streamlined approach enhances productivity and improves data management within the Salesforce environment.