### Run Development Server
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Start the development server to work on the project. This command is used for active development.
```shell
npm run dev
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Install global gulp CLI and project dependencies for development. Requires Node.js version 6 or higher.
```shell
npm install -g gulp-cli
npm install
```
--------------------------------
### Install @zwight/luckyexcel Package
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Install the @zwight/luckyexcel package using npm for use in ES modules or Node.js environments.
```shell
npm install @zwight/luckyexcel
```
--------------------------------
### Get Univer Snapshot
Source: https://github.com/zwight/luckyexcel/blob/master/assets/univer-import-export-script/index.html
A helper function to retrieve the current state (snapshot) of the active Univer workbook. It throws an error if the workbook has not been initialized.
```javascript
const getUniverSnapshot = () => {
const activeWorkbook = univerAPI.getActiveWorkbook();
if (!activeWorkbook) {
throw new Error('Workbook is not initialized');
}
return activeWorkbook.save();
};
```
--------------------------------
### Build Project for Production
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Compile and package the project for production deployment. This command generates the distributable files.
```shell
npm run build
```
--------------------------------
### Initialize Univer with Presets and Plugins
Source: https://github.com/zwight/luckyexcel/blob/master/assets/univer-import-export-script/index.html
Initializes a Univer instance with core and filter presets, custom menus for saving and importing, and locale configuration. The custom menus define callbacks for pre-import, post-import, and save actions.
```javascript
const { createUniver } = UniverPresets;
const { LocaleType, merge } = UniverCore;
const { defaultTheme } = UniverDesign;
const { UniverSheetsCorePreset } = UniverPresetSheetsCore;
const { UniverSheetsFilterPreset } = UniverPresetSheetsFilter
const { univerAPI, univer } = createUniver({
locale: LocaleType.ZH_CN,
locales: {
[LocaleType.ZH_CN]: merge(
{},
UniverPresetSheetsCoreZhCN,
UniverPresetSheetsFilterZhCN
),
},
theme: defaultTheme,
presets: [
UniverSheetsCorePreset(),
UniverSheetsFilterPreset(),
],
});
univer.registerPlugin(UniverSheetsCustomMenuPlugin, {
menu: [
CustomSaveMenu({
after: () => {
const saveData = getUniverSnapshot();
console.log(saveData);
},
}),
CustomImportMenu({
before: () => {
// loading.value = true;
},
after: ({ error }) => {
// loading.value = false;
if (error) {
console.error(error.message || '导入失败');
return;
}
console.info('导入成功');
},
}),
]
});
```
--------------------------------
### Initialize Demo Handler
Source: https://github.com/zwight/luckyexcel/blob/master/src/index.html
This function sets up event listeners for file uploads, demo file selection, and demo file downloads. It is designed to be called once to initialize the interactive demo features.
```javascript
function demoHandler(){
let upload = document.getElementById("Luckyexcel-demo-file");
let selectADemo = document.getElementById("Luckyexcel-select-demo");
let downlodDemo = document.getElementById("Luckyexcel-downlod-file");
let mask = document.getElementById("lucky-mask-demo");
if(upload){
window.onload = () => {
// Event listeners for upload, select, and download are defined here
// ... (details omitted for brevity, see other snippets for specific listeners)
}
}
}
demoHandler();
```
--------------------------------
### Download Demo XLSX File
Source: https://github.com/zwight/luckyexcel/blob/master/src/index.html
Attaches a 'click' event listener to a download button to initiate the download of a selected demo XLSX file. It creates an iframe to handle the download process.
```javascript
downlodDemo.addEventListener("click", function(evt){
var obj = selectADemo;
var index = obj.selectedIndex;
var value = obj.options[index].value;
if(value.length==0){
alert("Please select a demo file");
return;
}
var elemIF = document.getElementById("Lucky-download-frame");
if(elemIF==null){
elemIF = document.createElement("iframe");
elemIF.style.display = "none";
elemIF.id = "Lucky-download-frame";
document.body.appendChild(elemIF);
}
elemIF.src = value;
});
```
--------------------------------
### Create Univer Workbook
Source: https://github.com/zwight/luckyexcel/blob/master/assets/univer-import-export-script/index.html
Creates a new Univer workbook with a specified name. This is a fundamental step before performing operations on the spreadsheet.
```javascript
univerAPI.createWorkbook({ name: 'Test Sheet' }); // 创建一个名为 'Test Sheet' 的工作表
```
--------------------------------
### Initialize Luckysheet with Collaborative Editing
Source: https://github.com/zwight/luckyexcel/blob/master/assets/luckysheet/index.html
Initializes Luckysheet for collaborative editing. Requires gridKey from the URL or source code. Sets up update and load URLs for real-time collaboration.
```javascript
var lang = luckysheetDemoUtil.language() === 'zh' ? 'zh' : 'en';
var isShare = luckysheetDemoUtil.getRequest().share;
var gridKey = luckysheetDemoUtil.getRequest().gridKey;
var options = null;
if(isShare || gridKey){
if(!gridKey){
alert('If gridKey is not provided in the address bar, please add it in the source code')
}
options = {
container: "luckysheet",
lang: lang,
allowUpdate:true,
updateImageUrl: location.origin + "/luckysheet/api/updateImg",
updateUrl: "ws://"+ location.host +"/luckysheet/websocket/luckysheet",
gridKey: gridKey,
loadUrl: location.origin + "/luckysheet/api/load",
loadSheetUrl: location.origin + "/luckysheet/api/loadsheet"
}
}else{
options = {
container: 'luckysheet',
lang: lang,
forceCalculation:false,
plugins: ['chart'],
fontList: [
{
"fontName":"HanaleiFill",
"url":"./assets/iconfont/HanaleiFill-Regular.ttf"
},
{
"fontName":"Anton",
"url":"./assets/iconfont/Anton-Regular.ttf"
},
{
"fontName":"Pacifico",
"url":"./assets/iconfont/Pacifico-Regular.ttf"
}
],
hook:{
rowTitleCellRenderBefore:function(rowNum,postion,ctx){},
rowTitleCellRenderAfter:function(rowNum,postion,ctx){},
columnTitleCellRenderBefore:function(columnAbc,postion,ctx){},
columnTitleCellRenderAfter:function(columnAbc,postion,ctx){},
cellRenderBefore:function(cell,postion,sheetFile,ctx){},
cellRenderAfter:function(cell,postion,sheetFile,ctx){},
cellMousedownBefore:function(cell,postion,sheetFile,ctx){},
cellMousedown:function(cell,postion,sheetFile,ctx){},
sheetMousemove:function(cell,postion,sheetFile,moveState,ctx){},
sheetMouseup:function(cell,postion,sheetFile,moveState,ctx){},
cellAllRenderBefore:function(data,sheetFile,ctx){},
updated:function(operate){},
cellUpdateBefore:function(r,c,value,isRefresh){},
cellUpdated:function(r,c,oldValue, newValue, isRefresh){},
sheetActivate:function(index, isPivotInitial, is newSheet){},
rangeSelect:function(index, sheet){},
commentInsertBefore:function(r, c){},
commentInsertAfter:function(r, c, cell){},
commentDeleteBefore:function(r, c, cell){},
commentDeleteAfter:function(r, c, cell){},
commentUpdateBefore:function(r, c, value){},
commentUpdateAfter:function(r, c, oldCell, newCell ){},
cellEditBefore:function(range ){},
workbookCreateAfter:function(json){},
rangePasteBefore:function(range,data){ return false; }
}
}
}
luckysheet.create(options);
```
--------------------------------
### Import Excel to Univer Data Structure (CDN)
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Use this snippet to convert an Excel file into the Univer data structure when using the project via CDN. It requires Univer to be initialized separately.
```html
```
--------------------------------
### Import Excel to Univer Data Structure (ES Module)
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Import and use the `transformExcelToUniver` function to convert an Excel file to the Univer data structure within an ES module environment. Ensure the Excel file is obtained before calling this function.
```javascript
import LuckyExcel from '@zwight/luckyexcel'
// After getting the xlsx file
LuckyExcel.transformExcelToUniver(
file,
async (exportJson: any) => {
// Get the worksheet data after conversion
},
(error: any) => {
// handle error if any thrown
}
);
```
--------------------------------
### Import CSV to Univer Data Structure (CDN)
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Use this snippet to convert a CSV file into the Univer data structure when using the project via CDN. It requires Univer to be initialized separately.
```html
// Univer import CSV file
LuckyExcel.transformCsvToUniver(
file,
async (data: any) => {
// After obtaining the converted table data, use univer to initialize, or update the existing univer workbook
// Note: Univer needs to introduce dependent packages and initialize the table container before it can be used
univer.createUnit(
UniverInstanceType.UNIVER_SHEET,
data || {}
);
},
(error: any) => {
console.log(error);
}
);
```
--------------------------------
### Initialize LuckySheet
Source: https://github.com/zwight/luckyexcel/blob/master/src/index.html
This snippet shows how to initialize the LuckySheet component with custom options. Ensure the container element with the ID 'luckysheet' exists in your HTML.
```javascript
$(function () {
//Configuration item
var options = {
container: 'luckysheet', //luckysheet is the container id
showinfobar: false,
}
luckysheet.create(options)
});
```
--------------------------------
### Export Univer to XLSX File (CDN)
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Use this snippet to export Univer data to an XLSX file when using the project via CDN. The `getBuffer` option controls whether to download directly or return buffer data.
```html
// Export Univer to XLSX file
// getBuffer: true will not download the file, only return the file's buffer data, false will download directly
LuckyExcel.transformUniverToExcel({
snapshot,
fileName,
getBuffer: true,
success: (buffer: Buffer) => {
console.log('success');
},
error: (error: Error) => {
console.log('error', error);
},
});
```
--------------------------------
### Using Iconfont in HTML
Source: https://github.com/zwight/luckyexcel/blob/master/assets/luckysheet/assets/iconfont/demo_index.html
Demonstrates how to apply an Iconfont icon to an HTML element using its font encoding. Replace '3' with the specific character code for the desired icon.
```html
3
```
--------------------------------
### Load LuckyExcel Script with Fallback
Source: https://github.com/zwight/luckyexcel/blob/master/assets/univer-import-export-script/index.html
Loads the LuckyExcel UMD script, with a fallback to a local path if the primary source fails. This ensures the library is available even if CDN loading fails.
```javascript
(function loadScriptWithFallback() {
const primarySrc = '../../dist/luckyexcel.umd.js';
const backupSrc = 'luckyexcel.umd.js';
const script = document.createElement('script');
script.src = primarySrc;
// 加载失败时使用备用地址
script.onerror = function () {
console.warn('Primary script failed, loading fallback...');
const fallbackScript = document.createElement('script');
fallbackScript.src = backupSrc;
fallbackScript.onerror = function () {
console.error('Both script sources failed to load.');
};
document.head.appendChild(fallbackScript);
};
document.head.appendChild(script);
})();
```
--------------------------------
### Export Univer to CSV File (CDN)
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Use this snippet to export Univer data to a CSV file when using the project via CDN. The `getBuffer` option controls whether to download directly or return buffer data. The `sheetName` parameter allows specifying a single sheet for export.
```html
// Export Univer to CSV file
// snapshot is the Univer snapshot data, getBuffer: true will not download the file, only return the csv content, false will download directly
// sheetName: Because Univer may have multiple sheets, csv does not have sheets, if sheetName has a value, only the data of the specified sheet name will be downloaded. If it is not passed, all sheets will be downloaded. The file name is ${fileName}_${sheet.name}
LuckyExcel.transformUniverToCsv({
snapshot,
fileName,
getBuffer: true,
sheetName: snapshot.sheetOrder[0],
success: (buffer: string | { [key: string]: string }) => {
console.log('success');
},
error: (error: Error) => {
console.log('error', error);
},
});
```
--------------------------------
### transformExcelToUniver
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Converts an Excel file into the Univer data structure. It takes the file as input and provides a callback with the converted JSON data or an error.
```APIDOC
## transformExcelToUniver
### Description
Converts an Excel file into the Univer data structure. It takes the file as input and provides a callback with the converted JSON data or an error.
### Method
`LuckyExcel.transformExcelToUniver(file, successCallback, errorCallback)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **file** (File) - Required - The Excel file to be converted.
- **successCallback** (Function) - Required - Callback function that receives the converted Univer JSON data.
- **errorCallback** (Function) - Required - Callback function to handle any errors during conversion.
### Request Example
```javascript
LuckyExcel.transformExcelToUniver(
file,
async (exportJson) => {
// Process converted data
},
(error) => {
console.error(error);
}
);
```
### Response
#### Success Response
The `successCallback` receives the Univer JSON data structure.
#### Response Example
```json
{
// Univer JSON data structure
}
```
```
--------------------------------
### transformCsvToUniver
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Converts a CSV file into the Univer data structure. It takes the file as input and provides a callback with the converted data or an error.
```APIDOC
## transformCsvToUniver
### Description
Converts a CSV file into the Univer data structure. It takes the file as input and provides a callback with the converted data or an error.
### Method
`LuckyExcel.transformCsvToUniver(file, successCallback, errorCallback)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **file** (File) - Required - The CSV file to be converted.
- **successCallback** (Function) - Required - Callback function that receives the converted Univer JSON data.
- **errorCallback** (Function) - Required - Callback function to handle any errors during conversion.
### Request Example
```javascript
LuckyExcel.transformCsvToUniver(
file,
async (data) => {
// Process converted data
},
(error) => {
console.error(error);
}
);
```
### Response
#### Success Response
The `successCallback` receives the Univer JSON data structure.
#### Response Example
```json
{
// Univer JSON data structure
}
```
```
--------------------------------
### transformUniverToCsv
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Exports Univer data structure to a CSV file. Supports specifying a file name and sheet name, and can return the buffer or download the file directly.
```APIDOC
## transformUniverToCsv
### Description
Exports Univer data structure to a CSV file. Supports specifying a file name and sheet name, and can return the buffer or download the file directly.
### Method
`LuckyExcel.transformUniverToCsv({ snapshot, fileName, getBuffer, sheetName, success, error })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **snapshot** (Object) - Required - The Univer snapshot data.
- **fileName** (string) - Required - The desired name for the output CSV file.
- **getBuffer** (boolean) - Optional - If true, returns the CSV content as a buffer; otherwise, downloads the file directly. Defaults to false.
- **sheetName** (string) - Optional - The name of the sheet to export. If not provided, all sheets are exported.
- **success** (Function) - Required - Callback function upon successful export.
- **error** (Function) - Required - Callback function to handle any errors during export.
### Request Example
```javascript
LuckyExcel.transformUniverToCsv({
snapshot: univerSnapshotData,
fileName: 'my-data',
getBuffer: true,
sheetName: 'Sheet1',
success: (buffer) => {
console.log('CSV export successful:', buffer);
},
error: (error) => {
console.error('CSV export failed:', error);
}
});
```
### Response
#### Success Response
- **buffer** (string | Object) - If `getBuffer` is true, this contains the CSV content or an object mapping sheet names to CSV content. Otherwise, the file is downloaded directly.
#### Response Example
```json
// If getBuffer is true and multiple sheets are exported:
{
"Sheet1": "column1,column2\nvalue1,value2",
"Sheet2": "columnA,columnB\nvalueA,valueB"
}
// If getBuffer is true and a single sheet is exported:
"column1,column2\nvalue1,value2"
```
```
--------------------------------
### Iconfont @font-face Declaration
Source: https://github.com/zwight/luckyexcel/blob/master/assets/luckysheet/assets/iconfont/demo_index.html
Defines the font-face for Iconfont, specifying the font family and the paths to the font files. This is the first step to using Iconfont in your project.
```css
@font-face {
font-family: 'iconfont';
src: url('iconfont.eot');
src: url('iconfont.eot?#iefix') format('embedded-opentype'),
url('iconfont.woff2') format('woff2'),
url('iconfont.woff') format('woff'),
url('iconfont.ttf') format('truetype'),
url('iconfont.svg#iconfont') format('svg');
}
```
--------------------------------
### transformUniverToExcel
Source: https://github.com/zwight/luckyexcel/blob/master/README.md
Exports Univer data structure to an XLSX file. Supports specifying a file name and can return the file buffer or download the file directly.
```APIDOC
## transformUniverToExcel
### Description
Exports Univer data structure to an XLSX file. Supports specifying a file name and can return the file buffer or download the file directly.
### Method
`LuckyExcel.transformUniverToExcel({ snapshot, fileName, getBuffer, success, error })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **snapshot** (Object) - Required - The Univer snapshot data.
- **fileName** (string) - Required - The desired name for the output XLSX file.
- **getBuffer** (boolean) - Optional - If true, returns the file content as a buffer; otherwise, downloads the file directly. Defaults to false.
- **success** (Function) - Required - Callback function upon successful export.
- **error** (Function) - Required - Callback function to handle any errors during export.
### Request Example
```javascript
LuckyExcel.transformUniverToExcel({
snapshot: univerSnapshotData,
fileName: 'my-workbook',
getBuffer: true,
success: (buffer) => {
console.log('XLSX export successful:', buffer);
},
error: (error) => {
console.error('XLSX export failed:', error);
}
});
```
### Response
#### Success Response
- **buffer** (Buffer) - If `getBuffer` is true, this contains the XLSX file content as a Buffer. Otherwise, the file is downloaded directly.
#### Response Example
```json
// Buffer object representing the XLSX file content
```
```
--------------------------------
### Load XLSX File via Input Change
Source: https://github.com/zwight/luckyexcel/blob/master/src/index.html
Handles the 'change' event on a file input element to load and display an XLSX file using LuckyExcel.transformExcelToLucky. It validates the file type and updates the LuckySheet instance.
```javascript
upload.addEventListener("change", function(evt){
var files = evt.target.files;
if(files==null || files.length==0){
alert("No files wait for import");
return;
}
let name = files[0].name;
let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
if(suffix!="xlsx"){
alert("Currently only supports the import of xlsx files");
return;
}
LuckyExcel.transformExcelToLucky(files[0], function(exportJson, luckysheetfile){
if(exportJson.sheets==null || exportJson.sheets.length==0){
alert("Failed to read the content of the excel file, currently does not support xls files!");
return;
}
window.luckysheet.destroy();
window.luckysheet.create({
container: 'luckysheet', //luckysheet is the container id
showinfobar:false,
data:exportJson.sheets,
title:exportJson.info.name,
userInfo:exportJson.info.name.creator
});
});
});
```
--------------------------------
### Load Remote XLSX File from Select Change
Source: https://github.com/zwight/luckyexcel/blob/master/src/index.html
Handles the 'change' event on a select element to load a remote XLSX file by URL using LuckyExcel.transformExcelToLuckyByUrl. It displays a loading mask and updates the LuckySheet instance upon successful loading.
```javascript
selectADemo.addEventListener("change", function(evt){
var obj = selectADemo;
var index = obj.selectedIndex;
var value = obj.options[index].value;
var name = obj.options[index].innerHTML;
if(value==""){
return;
}
mask.style.display = "flex";
LuckyExcel.transformExcelToLuckyByUrl(value, name, function(exportJson, luckysheetfile){
if(exportJson.sheets==null || exportJson.sheets.length==0){
alert("Failed to read the content of the excel file, currently does not support xls files!");
return;
}
console.log(exportJson, luckysheetfile);
mask.style.display = "none";
window.luckysheet.destroy();
window.luckysheet.create({
container: 'luckysheet', //luckysheet is the container id
showinfobar:false,
data:exportJson.sheets,
title:exportJson.info.name,
userInfo:exportJson.info.name.creator
});
});
});
```
--------------------------------
### Iconfont CSS Styling
Source: https://github.com/zwight/luckyexcel/blob/master/assets/luckysheet/assets/iconfont/demo_index.html
Defines the CSS class for using Iconfont, setting the font family, size, and rendering properties. This class is applied to HTML elements to display the icons.
```css
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.