ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

How To Read Excel Data Using LWC Salesforce?

Home / Article & Blogs / Salesforce / Lightning / Lightning Web Components / How To Read Excel Data Using LWC Salesforce?
By khushmeet Kaur inLightning Web Components, Salesforce

We all know that Salesforce supports parsing the CSV file, but sometimes the client insists on uploading and parsing the data in the form of an excel file. The standard way this cannot be achieved.

Currently, we can use third-party plug-ins to meet this requirement.

1. Upload Static Resource

🔗 https://github.com/darkacer/myBatCave/blob/master/force-app/main/default/staticresources/sheetjs/sheetjs/sheetmin.js

Download the file from the above link and upload it under a static resource.

Import the static resource in the JS to read the content of the excel file.

2. Code Implementation

ExcelReader.html

<lightning-layout-item

size=”12″

small-device-size=”12″

large-device-size=”3″

medium-device-size=”4″

    padding=”around-small”>

    <lightning-input

type=”file”

label=”Upload

XLSX” name=”fileUploader”

        accept={strAcceptedFormats}

onchange={handleUploadFinished}>

    </lightning-input>

    <p>{strUploadFileName}</p>

</lightning-layout-item>

The indentation is missing

<lightning-layout-item size=”12″ small-device-size=”12″ large-device-size=”3″ medium-device-size=”4″

        padding=”around-small”>

        <lightning-input type=”file” label=”Upload XLSX” name=”fileUploader” accept={strAcceptedFormats}

            onchange={handleUploadFinished}>

        </lightning-input>

        <p>{strUploadFileName}</p>

</lightning-layout-item>

ExcelReader.js

import { LightningElement } from “lwc”;

/*Load the script to the component*/

import { loadScript } from “lightning/platformResourceLoader”;

/*Read the excel uploaded data*/

import excelFileReader from “@salesforce/resourceUrl/ExcelReaderPlugin”;

let XLS = {};

export default class ExcelFileReader extends LightningElement {

  /*Accepted formats for the excel file*/

  strAcceptedFormats = [“.xls”, “.xlsx”];

  strUploadFileName; //Store the name of the selected file.

  objExcelToJSON; //Javascript object to store the content of the file

  connectedCallback() {

    Promise.all([loadScript(this, excelFileReader)])

      .then(() => {

        XLS = XLSX;

      })

      .catch((error) => {

        console.log(“An error occurred while processing the file”);

      });

  }

  handleUploadFinished(event) {

    const strUploadedFile = event.detail.files;

    if (strUploadedFile.length && strUploadedFile != “”) {

      this.strUploadFileName = strUploadedFile[0].name;

      this.handleProcessExcelFile(strUploadedFile[0]);

    }

  }

  handleProcessExcelFile(file) {

    let objFileReader = new FileReader();

    objFileReader.onload = (event) => {

      let objFiledata = event.target.result;

      let objFileWorkbook = XLS.read(objFiledata, {

        type: “binary”

      });

      this.objExcelToJSON = XLS.utils.sheet_to_row_object_array(

        objFileWorkbook.Sheets[“Sheet1”]

      );

      //Verify if the file content is not blank

      if (this.objExcelToJSON.length === 0) {

        this.strUploadFileName = “”;

        this.dispatchEvent(

          new ShowToastEvent({

            title: “Error”,

            message: “Kindly upload the file with data”,

            variant: “error”

          })

        );

      }

      if (this.objExcelToJSON.length > 0) {

        //Remove the whitespaces from the javascript object

        Object.keys(this.objExcelToJSON).forEach((key) => {

          const replacedKey = key.trim().toUpperCase().replace(/\s\s+/g, “_”);

          if (key !== replacedKey) {

            this.objExcelToJSON[replacedKey] = this.objExcelToJSON[key];

            delete this.objExcelToJSON[key];

          }

        });

        console.log(‘objExcelToJSON’+objExcelToJSON);

      }

    };

    objFileReader.onerror = function (error) {

      this.dispatchEvent(

        new ShowToastEvent({

          title: “Error while reading the file”,

          message: error.message,

          variant: “error”

        })

      );

    };

    objFileReader.readAsBinaryString(file);

  }

}

The JS code

3. Testing

For testing, upload any excel file to the file uploader.

The sample file is mentioned below after uploading on the console panel the data of the excel file will be visible in the form of JSON Object.

RegionManagerSalesManItemUnitsUnit_priceSale_amt
EastMarthaAlexanderTelevision951,198.001,13,810.00
CentralHermannShelliHome5050025,000.00
CentralHermannLuisTelevision361,198.0043,128.00
CentralTimothyDavidCell Phone272256,075.00
WestTimothyStephenTelevision561,198.0067,088.00
EastMarthaAlexanderHome Theater60500.0030,000.00
CentralMarthaStevenTelevision751,198.0089,850.00
CentralHermannLuisTelevision901,198.001,07,820.00
WestDouglasMichaelTelevision321,198.0038,336.00

Note:- 

To create a record or manipulation of the JSON Object in Apex, desterilize the JSON object in Apex using a Wrapper Class.

For more updates regarding Salesforce or if you are looking for any Salesforce consultancy services, Contact ABSYZ Inc. at +1.415.364.8055 or +91 79979 66174. Visit our website at https://absyz.com/

70
Like this post
3 Posts
khushmeet Kaur

Search Posts

Archives

Categories

Recent posts

BioAsia 2023 in Hyderabad: An Annual International Event

BioAsia 2023 in Hyderabad: An Annual International Event

The Role Of Marketing in Small & Medium Enterprises

The Role Of Marketing in Small & Medium Enterprises

Salesforce For Retail: How Salesforce CRM Can Help Retailers

Salesforce For Retail: How Salesforce CRM Can Help Retailers

What is ChatGPT & How Does It Work?

What is ChatGPT & How Does It Work?

What Is Graphic Design? (Executive Summary 2023)

What Is Graphic Design? (Executive Summary 2023)

  • Previous PostUser Experience: Why it is so important and what you should know about it
  • Next PostLet's Meet at GITEX GLOBAL 2022 at DWTC – TECH EVENT IN DUBAI GITEX 2022 [Gulf Information Technology Exhibition]
    User Experience: Why it is so important and what you should know about it

Related Posts

Salesforce For Retail: How Salesforce CRM Can Help Retailers
Salesforce

Salesforce For Retail: How Salesforce CRM Can Help Retailers

Introduction To Copado Devops Tool
Salesforce

Introduction To Copado Devops Tool

What is Salesforce Code Builder?
Salesforce

What is Salesforce Code Builder?

Automation in Healthcare And Its Benefits
Health Cloud Salesforce

Automation in Healthcare And Its Benefits

Leave a Reply (Cancel reply)

Your email address will not be published. Required fields are marked *

*
*

ABSYZ Logo

INDIA | USA | UAE

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT