LuckySheet

一款完全开源在线的Excel编辑库,基本满足excel的操作,目前github的start高达15K

体验Demo

样式展示

LuckySheet

具体代码实现

本地使用的是umi脚手架,需要在document.ejs文件里面通过cdn方式引入

1
2
3
4
5
6
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/css/pluginsCss.css' />
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/plugins.css' />
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/css/luckysheet.css' />
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/assets/iconfont/iconfont.css' />
<script src="https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/plugins/js/plugin.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luckysheet@latest/dist/luckysheet.umd.js"></script>

这样就可以使luckysheet挂载在window下,然后就是写LuckySheet.tsx组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { useEffect } from 'react';

const luckyCss = {
margin: '0px',
padding: '0px',
position: 'absolute',
width: '100%',
height: '100%',
left: '0px',
top: '0px'
};

interface LuckysheetProps {
sheetData: any;
}

const Luckysheet = (props: LuckysheetProps) => {

const { sheetData } = props;

useEffect(() => {

const luckysheet = window.luckysheet;
luckysheet.create({
container: "luckysheet",
lang: 'zh', // 设定表格语言
data: sheetData
});
}, [sheetData]);

return (
<div id="luckysheet" style={luckyCss} ></div>
);

};

export default Luckysheet;

为了让初始数据进来,使用了sheetData来传入父组件的参数,sheetData的参数格式也是LuckySheet规定的格式

然后就是写父组件luckySheetShow.tsx, 编辑完表格数据之后,通过luckysheet?.getAllSheets()拿到表格数据,也就是子组件需要的sheetData,
存一份放在localStorage中,下次在当前页面也可以继续使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

import React, { useState } from 'react';
import Luckysheet from '@/components/LuckySheet';
import { Button } from 'antd';
import { initData } from './const';

function LuckySheetShow() {

const luckysheet = window.luckysheet;
const [sheetData, setSheetData] = useState<any>(initData);

const getData = () => {
const data = JSON.parse(window.localStorage.getItem('sheetData'));
setSheetData(data);
};

const saveData = () => {
const data = luckysheet?.getAllSheets();
window.localStorage.setItem('sheetData', JSON.stringify(data));
};

return (
<div className="App">
<Button onClick={saveData} style={{ zIndex: 1000 }}>保存数据</Button>
<Button onClick={getData} style={{ zIndex: 1000 }}>获取初始数据</Button>
<div style={{ height: '500px' }}></div>
<header className="App-header">
<Luckysheet sheetData={sheetData} />
</header>
</div>
);
}

export default LuckySheetShow

看了下这款在线编辑的API,功能还是十分强大的,如果有类似的需求,推荐使用