需求:在LWC中导入CSV数据,并动态显示字段。
因为本方法是使用Javascript对CSV文件进行解析,所以可能能够处理数据量更大一点
(没有验证过到底能够一次性导入多少条数据,请自行验证)
1,importCSV Lightning Web Component的作成
importCSV.js
页面的显示字段,不需要指定,直接使用CSV文件的第一行内容。
import { LightningElement, track } from 'lwc';
import SaveFile from '@salesforce/apex/ImportCSVHandler.SaveFile';
export default class CreateCSVTotable extends LightningElement {
@track isTrue = true;
@track showLoadingSpinner = false;
columns =[];
data = [];
handleCSVUpload(event) {
const files = event.detail.files;
//console.log("#### files = "+JSON.stringify(files));
if (files.length > 0) {
const file = files[0];
// start reading the uploaded csv file
this.read(file);
}
}
async read(file) {
try {
const result = await this.load(file);
//console.log("#### result = "+JSON.stringify(result));
// execute the logic for parsing the uploaded csv file
this.parseCSV(result);
} catch (e) {
this.error = e;
}
}
async load(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
//console.log("#### reader.result = "+JSON.stringify(reader.result));
this.isTrue = false;
resolve(reader.result);
};
reader.onerror = () => {
this.isTrue = true;
//console.log("#### reader.error = "+JSON.stringify(reader.error));
reject(reader.error);
};
//console.log("#### file = "+JSON.stringify(file));
reader.readAsText(file);
});
}
parseCSV(csv) {
// parse the csv file and treat each line as one item of an array
const lines = csv.split(/\r\n|\n/);
//console.log("#### lines = "+JSON.stringify(lines));
// parse the first line containing the csv column headers
const headers = lines[0].split(',');
console.log("#### headers = "+JSON.stringify(headers));
// iterate through csv headers and transform them to column format supported by the datatable
this.columns = headers.map((header) => {
return { label: header, fieldName: header };
});
//console.log("#### this.columns = "+JSON.stringify(this.columns));
const data = [];
// iterate through csv file rows and transform them to format supported by the datatable
lines.forEach((line, i) => {
if (i === 0) return;
const obj = {};
const currentline = line.split(',');
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
data.push(obj);
});
//console.log("#### data = "+JSON.stringify(data));
// assign the converted csv data for the lightning datatable
this.data = data;
}
handleSave(){
if(!this.isTrue){
this.showLoadingSpinner = true;
SaveFile({ jsonString: JSON.stringify(this.data)})
.then(result => {
this.showLoadingSpinner = false;
if(result=='SUCCESS'){
this.isTrue = true;
this.dispatchEvent(
new ShowToastEvent({
title: 'Success!!',
message: this.file.name + ' - Uploaded Successfully!!',
variant: 'success',
}),
);
}
else{
this.showLoadingSpinner = false;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: result,
variant: 'error',
}),
);
}
})
.catch(error=>{
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: error.message,
variant: 'error',
}),
);
});
}
}
}
importCSV.html
<template>
<template if:true={showLoadingSpinner}>
<div style="z-index: 10000 !important;">
<lightning-spinner alternative-text="Uploading......" size="medium" style="z-index: 10000 !important;"></lightning-spinner>
</div>
</template>
<lightning-card title="CSV To Datatable" icon-name="doctype:csv">
<div class="slds-p-around_medium">
<lightning-input type="file" label="Please upload a UTF-8 encoded, comma separated .csv file" accept=".csv"
onchange={handleCSVUpload}>
</lightning-input>
<div>
<lightning-button class="slds-m-top--medium" label="Import Data" onclick={handleSave} variant="brand" disabled={isTrue}></lightning-button>
</div>
</div>
<div style="height: 500px">
<lightning-datatable key-field="Id" data={data} columns={columns} hide-checkbox-column>
</lightning-datatable>
</div>
</lightning-card>
</template>
importCSV.js-meta.xml的内容
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__UtilityBar</target>
<target>lightning__FlowScreen</target>
<target>lightningCommunity__Page</target>
<target>lightningCommunity__Default</target>
</targets>
</LightningComponentBundle>
2,ImportCSVHandler.cls的作成
ImportCSVHandler.cls
因为是直接使用DataTable中的 data={data}数据,
所以无需再指定具体的字段,所以说这个方法更方便。
public with sharing class ImportCSVHandler {
@AuraEnabled
public static string SaveFile(string jsonString){
string sMessage='';
try {
List<Account> lstACCToInsert=(List<Account>)JSON.deserialize(jsonString, List<Account>.class);
insert lstACCToInsert;
sMessage='SUCCESS';
} catch (Exception e) {
sMessage=e.getMessage();
}
return sMessage;
}
}
执行效果
准备工作 创建如下CSV文件
Name,Rating,Type,Industry,Ownership
GogogoAccount04,Hot,Prospect,Agriculture,Public
效果如下
参考文章
代码原地址,本文章对代码会作稍微的修改,方便大家理解 。
下面的代码只有动态识别CSV的功能,没有数据创建功能,本文章补足了创建数据的处理。
https://www.avnishyadav.com/2023/01/how-to-build-simple-csv-parser-with.html