In the management background, we will use a large number of Table form components, import and export various reports, some scenarios also need to report data visualization analysis, dynamic generation of visual charts, the author will be based on the above scenarios, summarize some practical Table component development skills, so that the front-end development is no longer difficult.
Past classic
- Easily teach you how to drag and drop components, scale, scale multiple control points and drag data to report
- Visual drag-and-drop platform design based on natural flow layout
- H5-dooring is a h5 page visualization editor based on React+Koa
Results demonstrate
Technical point
- Achieve dynamic rendering of Table
- Table sort, multi – column sort, custom search
- Import Excel data rendering tables in batches
- Export the Table data as an Excel file
- Automatically generate multidimensional visual reports based on Table data
- Implement a simple Table editor
The above are several commonly used business scenarios, the next author with you to achieve one by one.
The technical implementation
1. The implementationTableDynamic rendering
Generally, we render the table, and most of them write the table structure in advance, rather than define columns first and then request data to fill the table in the back end, as follows:
const columns = [
{
title: 'name'.dataIndex: 'name'.key: 'name'}, {title: 'age'.dataIndex: 'age'.key: 'age'}, {title: 'address'.dataIndex: 'address'.key: 'address',},];const dataSource = [
{
key: '1'.name: 'Xu Xiaoxi'.age: 18.address: 'Hangzhou Xihu District',}];<Table dataSource={dataSource} columns={columns} />
Copy the code
Although this business scenario can meet the Table requirements of most background management systems, and can also be built using ANTD or Element, many modules are uncertain for lowcode system, and we need to drive Table rendering according to protocol and data.
Let’s say we’re inH5-DooringWe need to statistically analyze the data of the form. Since the form items are uncertain, we cannot define one in advancetable schema.
How to render the Table dynamically? Here to provide you with a train of thought, based on data driven + protocol layer constraints. Similar to the low code platform of foreign SAP, which is completely based on oDATA protocol, we can constrain the submitted data format of the form, and then dynamically extract the columns required by the Table in combination with the data submitted by the user, and finally render the Table component.
The protocol layerThe main constraints on the display type of different fields, such as strings, buttons, links, labels, etc., the user will carry the corresponding protocol layer after submitting the formflagAnd the value entered by the user, which is good for our parser to renderTableYou can display different types for different columns. As follows:
The author here simple implementation of a demo, as follows:
// table Data source
let tableData = res.map((item:any,i:number) = > ({ ID: nanoid(8), ...item }));
let baseRow = tableData[0],
keys = Object.keys(baseRow);
setColumns(() = > {
const baseColumn = keys.map(item= > {
return {
title: item,
dataIndex: item,
key: item,
width: item === 'ID' ? 0 : null.render: (v:any) = > {
if(typeof v === 'object') {
return <>
{
v.map(item => <Tag color="#2F54EB">{ item.label || item }</Tag>)}</>
}
return item === 'ID' ? ' ' : v
}
}
})
baseColumn.push({
title: 'operation'.key: 'operation'.fixed: 'right'.width: 100.render: (row) = > <a onClick={()= >HandleDel (row)} > delete</a>,})return baseColumn
})
Copy the code
Above, we have implemented a dynamic Table rendering scheme. React is used in this case, and you can also use the familiar Vue3.0.
2. TableSort, multi – column sort, custom search
TableSorting, multi-column sorting is easy to implement, we just have to customize itTableHeader, the sort field is promoted toTableThe publicState
Finally, the sorting identification and sorting method can be used to sort. At present, ANTD4.0 has supported multi-column sorting, you can directly refer to learning, as follows:For custom searches, this is at the beginning of this articledemoFor the displayed column search, we can use the following solution:
const getColumnSearchProps = dataIndex= > ({
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) = > (
<div style={{ padding: 8}} >
<Input
ref={node= > {
searchInput = node;
}}
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
style={{ width: 188, marginBottom: 8, display: 'block' }}
/>
<Space>
<Button
type="primary"
onClick={()= > handleSearch(selectedKeys, confirm, dataIndex)}
icon={<SearchOutlined />} size="small" style={{width: 90}}</Button>
<Button onClick={()= >HandleReset (clearFilters)} size="small" style={{width: 90}}</Button>
</Space>
</div>
),
filterIcon: filtered= > <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined}} / >,
onFilter: (value, record) = >
record[dataIndex]
? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
: ' '.onFilterDropdownVisibleChange: visible= > {
if (visible) {
setTimeout(() = > searchInput.select(), 100); }},render: text= >
searchedColumn === dataIndex ? (
<Highlighter
highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
searchWords={[searchText]}
autoEscape
textToHighlight={text ? text.toString(a):"'} / >
) : (
text
),
});
Copy the code
At this point, we only need to add custom headers to each column of dynamically generated columns:
{
title: item,
dataIndex: item,
key: item, ... getColumnSearchProps(item) }Copy the code
antd4.0There are also detailed ways to use, here the author is not a introduction, the effect is as follows:You can alsoH5-DooringView the specific effect in the management background.
3. Import data in batchesExcelData renderingTable
In the background of a lot of data analysis we need to deal with a lot of spreadsheets, manual entry with the traditional Excel will be slowly obsolete. For example, different channels have collected a lot of business data, sorting into Excel, then how to quickly save to their own background system? The general idea is as follows:
- Input one by one in the form
- Background parsing files are processed into standard data structures that can be stored in the library
- Front-end implementation of an import excel, automatic data synchronization
The first scheme is inefficient and suitable for manual entry of C-end users, so we will ignore it temporarily. The author will implement the third scheme. The implementation idea is as follows:
Here we use the XLSX library, combined with the FileReader API. We get the binary data of Excel file through FileReader, and then pass it to XLSX to parse into JS Object. Finally, we generate the table data structure conforming to the specification through the table renderer written by the author. The source code is as follows:
// Parse and extract excel data
let reader = new FileReader();
reader.onload = function(e) {
let data = e.target.result;
let workbook = XLSX.read(data, {type: 'binary'});
let sheetNames = workbook.SheetNames; // Set of worksheet names
let draftArr = {}
sheetNames.forEach(name= > {
let worksheet = workbook.Sheets[name]; // The specified worksheet can only be obtained by the worksheet name
for(let key in worksheet) {
// v reads the original value of the cell
if(key[0]! = ='! ') {
if(draftArr[key[0]]) {
draftArr[key[0]].push(worksheet[key].v)
}else {
draftArr[key[0]] = [worksheet[key].v]
}
}
}
});
// Obtain the valid data product of the table
const sourceData = Object.values(draftArr);
}
reader.readAsBinaryString(file);
Copy the code
After obtaining a valid table data source, we can perform the dynamic rendering of the table logic described in section 1.
With the above method, we can achieve any structure of the Excel table import. After the import we can automatically send the request to store in our business background.
4. WillTableData exported asExcel
Similarly, we introduced importing Excel to tables, and we can export tables to Excel for data distribution and localization, such as our recent popular online document applications. The author here briefly talk about the realization of ideas:
The author uses the jS-export-Excel library to generate Excel files, and based on it, the author realizes an out-of-the-box method to avoid people’s brain building wheels. As follows:
import ExportJsonExcel from 'js-export-excel';
const generateExcel = () = > {
let option:any = {}; // Option stands for the Excel file
let dataTable = []; // The data content in the Excel file
let len = list.length;
if (len) {
for(let i=0; i<len; i++) {
let row = list[i];
let obj:any = {};
for(let key in row) {
if(typeof row[key] === 'object') {
let arr:any = row[key];
obj[key] = arr.map((item:any) = > (typeof item === 'object' ? item.label : item)).join(', ')}else {
obj[key] = row[key]
}
}
dataTable.push(obj); // Set the data source for each column in Excel}}let tableKeys = Object.keys(dataTable[0]);
option.fileName = tableName; // Excel file name
option.datas = [
{
sheetData: dataTable, // The data source in the Excel file
sheetName: tableName, // Name of the sheet page in the Excel file
sheetFilter: tableKeys, // Column data to be displayed in the Excel file
sheetHeader: tableKeys, // The header name of each column in the Excel file}]let toExcel = new ExportJsonExcel(option); // Generate the Excel file
toExcel.saveExcel(); // Download the Excel file
}
Copy the code
Based on 5.TableData automatically generates multidimensional visual reports
In the background management system and BI platform, we will encounter a lot of requirements for data analysis and report display. Next, the author will introduce how to dynamically generate multidimensional visual analysis reports based on Table data.
I introduced the concept of measurement rows in a previous article. For data analysis, we also need to consider the concept of analyzable dimensions, such as what is analyzable and what is not. For example, we have another table with the following structure:For contact information, it is not measurable, that is, there is no value to analyze this item, so in the automatic generation of multidimensional analysis, we theoretically do not analyze it, based on this principle, we design a simple automatic generation of multidimensional visual report scheme.
5.1 Obtaining Dimension Data Based on data Sources
We measure the dimensions with scope attributes and generate measurement data with the following code:
const generateDistData = (key:string, list:any) = > {
let distDataMap:any = {},
distData = []
list.forEach((item:any) = > {
// The current latitude category
let curKey = typeof item[key] === 'object' ? item[key][0].label : item[key];
if(distDataMap[curKey]) {
distDataMap[curKey]++;
}else {
distDataMap[curKey] = 1; }})// Generate the target array
for(let key in distDataMap) {
distData.push({name: key, value: distDataMap[key]})
}
return distData
}
Copy the code
At this time, we only need to obtain the data value of a certain dimension according to the field of the dimension, and then render it through the visual component.
5.2 Generating visual reports based on a certain dimension
We used @ant-design/ Charts with the following code:
<div className={styles.anazlyHeader}>
<div className={styles.anazlyItem}>
<span>Analyze latitude:</span>
<Select style={{ width: 120 }} onChange={(v)= > handleAnazlyChange(0, v)} defaultValue={keys[0]}>
{
keys.map((item,i) => {
return <Option value={item} key={i}>{ item }</Option>})}</Select>
</div>
</div>
<div className={styles.anazlyContent}>{!!!!! config &&<Pie {. config} / >
}
</div>
Copy the code
The results are as follows:
6. Simple implementationTableThe editor
In fact, the author has analyzed in detail how to generate multi-dimensional data visualization analysis report with one key in the front end, which has also been integrated in h5-Dooring’s visual component editor. The specific demo is as follows:
You can study it if you are interested.
The last
I’m also working on an ongoing update to H5 editor H5-Dooring, and recently took a look at the features:
- Fix photo gallery selection bug
- Add provincial and municipal joint components
- Added the ability to import Excel data in batches
- Add custom form validation
- Audio components to add automatic play control, looping configuration items
- Add a horizontal slide component
Find it useful? Like the collection, by the way, click like it, your support is my biggest encouragement! Wechat search “interesting talk front end”, found more interesting H5 games, Webpack, node, gulp, CSS3, javascript, nodeJS, Canvas data visualization front-end knowledge and practical.