Skip to main content

Salesforce LWC

Salesforce apps can use third-party libraries in "Lightning Web Components".Salesforce应用程序可以使用“Lightning Web Components”中的第三方库。

This demo assumes familiarity with Lightning Web Components. 本演示假设您熟悉Lightning Web组件。Salesforce has a detailed introduction.Salesforce有详细的介绍

caution

Some of the details may differ across releases of Salesforce. 不同版本的Salesforce的某些细节可能有所不同。This demo is based on Lightning API version 55.0 and was last tested on 2022 June 26.此演示基于Lightning API 55.0版本,最后一次测试是在2022年6月26日。

Salesforce may change the platform in backwards-incompatible ways, so the demo may require some adjustments. Salesforce可能会以向后不兼容的方式更改平台,因此演示可能需要一些调整。The official documentation should be consulted.应查阅官方文件。

Getting Started入门

This demo was built on a "Developer Edition" account. 此演示基于“开发者版”帐户。At the time of writing, an account can be created for free.在撰写本文时,可以免费创建一个帐户

Create Sample Project and Component创建示例项目和组件

Following the steps in "Develop in Non-Scratch Orgs":遵循“在非划痕组织中开发”中的步骤:

## Login 
sfdx force:auth:web:login -d -a LWC-Hub

## Create Sample Project and Component
sfdx force:project:create --projectname SheetForce
cd SheetForce
sfdx force:lightning:component:create --type lwc -n sheetComponent -d force-app/main/default/lwc

By default, the component will not be available to app pages. 默认情况下,应用程序页面将无法使用该组件。A few files must be changed:必须更改一些文件:

force-app\main\default\lwc\sheetComponent\sheetComponent.html add some HTML:添加一些HTML:

<template>
<b>SheetForce demo</b>
</template>

force-app\main\default\lwc\sheetComponent\sheetComponent.js-meta.xml change isExposed from false to true and add some metadata:isExposedfalse更改为true,并添加一些元数据:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>SheetForce</masterLabel>
<description>SheetJS Demo</description>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>

Deploy Sample Project部署示例项目

Deploy the project:部署项目:

sfdx force:source:deploy -p force-app -u [email protected] USER .NAME  # replace with actual username

The custom component can be found in Custom Code > Lightning Components.自定义组件可以在自定义代码>突出组件中找到。

Custom Component

Initialize App Page初始化应用程序页面

Create an "App Page" in the "Lightning App Builder". 在“Lightning App Builder”中创建“应用程序页面”。Instructions are included in Hello World in a Scratch Org说明包含在一个Scratch组织的Hello World中。

The following options should be set:应设置以下选项:

  • The "App Page" option should be selected.应选择“应用程序页面”选项。
  • The App Label should be set to "SheetJS Demo".应用程序标签应设置为“SheetJS Demo”。
  • The "One Region" layout should be selected.应选择“一个区域”布局。

Under Custom components, you should see "SheetForce". 在“自定义零部件”下,您应该看到“SheetForce”。Click and drag it into the app builder main view to add it to the page.单击并将其拖动到app builder主视图中,将其添加到页面中。

Click "Save" and click "Yes" to activate. 单击“保存”,然后单击“是”激活。The following options should be set:应设置以下选项:

  • Click "Change..." next to "Icon" and pick a memorable icon单击“更改…”在“图标”旁边,选择一个值得纪念的图标
  • Under "Lightning Experience" click "LightningBolt" then "Add page to app"在“Lightning体验”下,单击“LightningBolt”,然后单击“将页面添加到应用程序”

Click "Save" to activate the page, then click the left arrow to return to Setup.单击“保存”激活页面,然后单击左箭头返回设置。

Click the App Launcher and select "Bolt Solutions" then "SheetJS Demo". 单击应用程序启动器并选择“Bolt Solutions”,然后选择“SheetJS Demo”。You should see a page like你应该看到这样的页面

SheetForce Demo

Adding the Standalone Script添加独立脚本

The standalone script can be downloaded and added as a static resource. 可以下载独立脚本并将其作为静态资源添加。Due to Salesforce naming restrictions, it will have to be renamed to sheetjs.js when adding the static resource.由于Salesforce命名限制,在添加静态资源时必须将其重命名为sheetjs.js

1) Download 下载https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js

warning警告

DO NOT "COPY AND PASTE"!不要“复制粘贴”! The file should be explicitly downloaded. 应明确下载该文件。Copying and pasting corrupts the source code and the component will fail in subtle ways.复制和粘贴会破坏源代码,组件会以微妙的方式失败。

The easiest approach is to right-click the link and select "Save Link As..."最简单的方法是右键单击链接并选择“将链接另存为…”

2) Move the file to the force-app/main/default/staticresources/ folder and rename the file to sheetjs.js.将文件移动到force-app/main/default/staticresources/,并将文件重命名为sheetjs.js

3) Create force-app/main/default/staticresources/sheetjs.resource-meta.xml:创建force-app/main/default/staticresources/sheetjs.resource-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
<cacheControl>Private</cacheControl>
<contentType>application/javascript</contentType>
</StaticResource>

4) Deploy the project again:再次部署项目:

sfdx force:source:deploy -p force-app -u SALESFORCE@USER.NAME # replace with actual username
note

The official documentation recommends adding a static resource with a ZIP file. 官方文档建议添加带有ZIP文件的静态资源。That approach is not explored in this demo.本演示中没有探讨这种方法。

Custom Code > Static Resources should now list sheetjs:自定义代码>静态资源现在应该列出sheetjs

Static Resources

Test the Static Resource测试静态资源

The script can be loaded from component code with:可以使用以下命令从组件代码加载脚本:

import XLSX from '@salesforce/resourceUrl/sheetjs';

The library includes a version number that can be displayed:该库包括一个版本号,可以显示:

1) Add a reference in sheetComponent.js and expose the version property:sheetComponent.js中添加引用并公开version属性:

import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import sheetjs from '@salesforce/resourceUrl/sheetjs';

export default class SheetComponent extends LightningElement {
version = "???"; // start with ???
async connectedCallback() {
await loadScript(this, sheetjs); // load the library
// At this point, the library is accessible with the `XLSX` variable
this.version = XLSX.version;
}
}

2) Reference the variable in sheetComponent.html:引用sheetComponent.html中的变量:

<template>
<b>SheetForce {version}</b>
</template>

3) Deploy the project again and re-load the Bolt Solutions "SheetJS Demo" page:再次部署项目并重新加载螺栓解决方案“SheetJS演示”页面:

Version number

Exporting Data from SF Lists从SF列表导出数据

note

There are many different data types and APIs. 有许多不同的数据类型和API。This demo uses the deprecated getListUi function to pull account data.此演示使用不推荐使用的getListUi函数来提取帐户数据。

Steps步骤

Getting Account Data获取帐户数据

The main method to obtain data is getListUi and the key for account data is ACCOUNT_OBJECT:获取数据的主要方法是getListUi,账号数据的键是ACCOUNT_OBJECT

import { getListUi } from 'lightning/uiListApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

// ...

export default class SheetComponent extends LightningElement {
@wire(getListUi, {
objectApiName: ACCOUNT_OBJECT.objectApiName,
listViewApiName: 'AllAccounts'
}) listInfo({ error, data }) {

// LIST DATA AVAILABLE HERE

};
// ...
}

Generating an Array of Arrays生成数组的数组

SheetJS most reliably translates "arrays of arrays", a nested array which directly maps to individual cell addresses. SheetJS最可靠地翻译“数组的数组”,一个直接映射到单个单元格地址的嵌套数组。For example:例如:

var data = [
["Name", "Phone"], // row 1
["Foo Bar", "(555) 555-5555"], // row 2
["Baz Qux", "(555) 555-5556"] // row 3
];

The APIs typically return nested objects, so the array must be constructed.API通常返回嵌套对象,因此必须构造数组。

Salesforce RepresentationSalesforce代表 (click to show)

The data parameter in the callback has a deep structure. 回调中的data参数具有深层结构。Typically one would set a property in the component and display data in a template:通常会在组件中设置属性并在模板中显示数据:

  // ...
// declare records variable in the component
records;
@wire(getListUi, {
objectApiName: ACCOUNT_OBJECT.objectApiName,
listViewApiName: 'AllAccounts'
}) listInfo({ error, data }) {
if (data) {
// data.records.records is the array of interest
this.records = data.records.records;
this.error = undefined;
}
}
// ...

The template itself would iterate across the records:模板本身将遍历记录:

<template>
<template if:true={records}>
<table>
<tr><th>Name</th><th>Phone</th></tr>
<template for:each={records} for:item="record">
<tr key={record.fields.Id.value}>
<td>{record.fields.Name.value}</td>
<td>{record.fields.Phone.value}</td>
</tr>
</template>
</table>
</template>
</template>

A suitable SheetJS array of arrays can be constructed by mapping across records:可以通过跨记录映射来构造合适的数组数组:

      var headers = [ "Name", "Phone" ];
this.aoa = [headers].concat(data.records.records.map(record => [
record.fields.Name.value, // Name field
record.fields.Phone.value, // Phone field
]));

This is readily exported to a spreadsheet in a callback function:这很容易在回调函数中导出到电子表格:

  @api async download() {
await loadScript(this, sheetjs); // load the library
// create workbook
var wb = XLSX.utils.book_new();
var ws = XLSX.utils.aoa_to_sheet(this.aoa);
XLSX.utils.book_append_sheet(wb, ws, "Data");
// export
XLSX.writeFile(wb, "SheetForceExport.xlsx");
};

Complete Example完整示例

1) Add a button to sheetComponent.html that will call a download callback:sheetComponent.html添加一个按钮,该按钮将调用download回调:

<template>
<!-- if the `aoa` property is set, show a button -->
<template if:true={aoa}>
<button onclick={download}><b>Click to Export!</b></button>
</template>
<!-- if the `aoa` property is not set, show a message -->
<template if:false={aoa}><b>Please wait for data to load ...</b></template>
</template>

2) Replace sheetComponent.js with the following:sheetComponent.js替换为以下内容:

import { LightningElement, wire, api } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import { getListUi } from 'lightning/uiListApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

import sheetjs from '@salesforce/resourceUrl/sheetjs';

export default class SheetComponent extends LightningElement {
aoa; // will hold data for export
@wire(getListUi, {
objectApiName: ACCOUNT_OBJECT.objectApiName,
listViewApiName: 'AllAccounts'
}) listInfo({ error, data }) {
if (data) {
var headers = [ "Name", "Phone" ];
// create AOA and assign to `aoa` property
this.aoa = [headers].concat(data.records.records.map(record => [
record.fields.Name.value, // Name field
record.fields.Phone.value, // Phone field
]));
} else if (error) console.log(error);
};
@api async download() {
await loadScript(this, sheetjs); // load the library
// create workbook
var wb = XLSX.utils.book_new();
var ws = XLSX.utils.aoa_to_sheet(this.aoa);
XLSX.utils.book_append_sheet(wb, ws, "Data");
// export
XLSX.writeFile(wb, "SheetForceExport.xlsx");
};
}

3) Re-deploy and refresh the app page:重新部署并刷新应用程序页面:

SF Export Button

The simple export has all of the data:简单导出包含所有数据:

Excel Export

note

SheetJS Pro offers additional styling options like cell styling, automatic column width calculations, and frozen rows.提供其他样式选项,如单元格样式、自动列宽计算和冻结行。