### Install development dependencies
Source: https://github.com/dream-num/luckyexcel/blob/master/README.md
Install global Gulp CLI and project-specific dependencies for development.
```shell
npm install -g gulp-cli
npm install
```
--------------------------------
### Install Luckyexcel via npm
Source: https://github.com/dream-num/luckyexcel/blob/master/README.md
Install the Luckyexcel package using npm for use in ES modules or Node.js projects.
```shell
npm install luckyexcel
```
--------------------------------
### Run development build
Source: https://github.com/dream-num/luckyexcel/blob/master/README.md
Execute the development build script to start the development server or build process.
```shell
npm run dev
```
--------------------------------
### Luckysheet Cell Data Structure
Source: https://github.com/dream-num/luckyexcel/blob/master/dist/luckysheet/index.html
Example of the JSON structure representing cell formatting, text rotation, and calculation chains within Luckysheet.
```json
"c":10,"v":{"bg":null,"bl":0,"it":0,"ff":0,"fs":11,"fc":"rgb(51, 51, 51)","ht":1,"vt":1}},{"r":29,"c":0,"v":{"ct":{"fa":"General","t":"inlineStr","s":[{"ff":"\"times new roman\"","fc":"rgb(51, 51, 51)","fs":"12","cl":0,"un":0,"bl":1,"it":0,"v":"TextRotate"}]},"ht":"1","vt":"0"}},{"r":29,"c":2,"v":{"ct":{"fa":"General","t":"g"},"v":"I am Luckysheet text rotate style","m":"I am Luckysheet text rotate style","tr":"1","tb":"2","ht":"1","fs":"12"}},{"r":29,"c":3,"v":{"ct":{"fa":"General","t":"g"},"v":"I am Luckysheet text rotate style","m":"I am Luckysheet text rotate style","tr":"2","tb":"2","ht":"0","fs":"12"}},{"r":29,"c":4,"v":{"ct":{"fa":"General","t":"g"},"v":"I am Luckysheet text rotate style","m":"I am Luckysheet text rotate style","tr":"4","tb":"2","ht":"1","fs":"12","vt":"2"}},{"r":29,"c":5,"v":{"ct":{"fa":"General","t":"g"},"v":"I am Luckysheet text rotate style","m":"I am Luckysheet text rotate style","tr":"5","tb":"2","ht":"1","fs":"12"}},{"r":29,"c":6,"v":{"ct":{"fa":"General","t":"g"},"v":"I am Luckysheet text rotate style","m":"I am Luckysheet text rotate style","tr":"1","tb":"1","ht":"1","fs":"12","vt":"0"}},{"r":30,"c":0,"v":{"ct":{"fa":"General","t":"g"},"v":"hidden1","m":"hidden1"}},{"r":31,"c":0,"v":{"m":"hidden2","ct":{"fa":"General","t":"g"},"v":"hidden2"}},{"r":33,"c":0,"v":{"ct":{"fa":"General","t":"g"},"bg":null,"bl":1,"it":0,"ff":0,"fs":11,"fc":"rgb(51, 51, 51)","ht":1,"vt":1}}], "ch_width": 2361, "rh_height": 936, "luckysheet_select_save": [ { "left": 741, "width": 138, "top": 796, "height": 19, "left_move": 741, "width_move": 138, "top_move": 796, "height_move": 19, "row": [ 33, 33 ], "column": [ 6, 6 ], "row_focus": 33, "column_focus": 6 } ], "calcChain": [ { "r": 0, "c": 3, "index": "0", "func": [ true, 3, "=Formula!A1+Formula!B1" ], "color": "w", "parent": null, "chidren": {}, "times": 0 } ], "scrollLeft": 0, "scrollTop": 0 }]
```
--------------------------------
### ES Module Import for Modern JavaScript
Source: https://context7.com/dream-num/luckyexcel/llms.txt
Integrate Luckyexcel into modern JavaScript applications using ES modules. This example shows usage within a React component for file uploads and a Vue component for promise-based conversion.
```javascript
import LuckyExcel from 'luckyexcel';
// React component example
function ExcelImporter({ onImport }) {
const handleFileChange = async (event) => {
const file = event.target.files[0];
if (!file) return;
if (!file.name.endsWith('.xlsx')) {
alert('Please select an .xlsx file');
return;
}
LuckyExcel.transformExcelToLucky(
file,
(exportJson, rawJson) => {
// Validate the conversion result
if (!exportJson.sheets || exportJson.sheets.length === 0) {
console.error('No valid sheets found');
return;
}
// Pass data to parent component
onImport({
info: exportJson.info,
sheets: exportJson.sheets,
raw: rawJson
});
},
(error) => {
console.error('Import error:', error);
alert(`Failed to import: ${error.message}`);
}
);
};
return (
);
}
// Vue component example
export default {
methods: {
importExcel(file) {
return new Promise((resolve, reject) => {
LuckyExcel.transformExcelToLucky(
file,
(exportJson) => resolve(exportJson),
(error) => reject(error)
);
});
}
}
};
```
--------------------------------
### Package the project
Source: https://github.com/dream-num/luckyexcel/blob/master/README.md
Run the build script to package the project for production.
```shell
npm run build
```
--------------------------------
### Initialize Luckysheet
Source: https://github.com/dream-num/luckyexcel/blob/master/dist/luckysheet/index.html
Use this method to initialize the Luckysheet instance with provided configuration options.
```javascript
luckysheet.create(options);
```
--------------------------------
### Initialize Luckysheet with Options
Source: https://github.com/dream-num/luckyexcel/blob/master/assets/luckysheet/index.html
Initializes Luckysheet with various configuration options, including language, collaborative editing settings, and custom fonts. This is the primary method for setting up a new spreadsheet instance.
```javascript
var options = null;
if(isShare || gridKey){
// http://localhost:3000/?gridKey=12eyy789-kk45ofid-23737245
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{
// http://localhost:3000/
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){ // console.log(rowNum);
},
rowTitleCellRenderAfter:function(rowNum,postion,ctx){ // console.log(ctx);
},
columnTitleCellRenderBefore:function(columnAbc,postion,ctx){ // console.log(columnAbc);
},
columnTitleCellRenderAfter:function(columnAbc,postion,ctx){ // console.log(postion);
},
cellRenderBefore:function(cell,postion,sheetFile,ctx){ // console.log(cell,postion,sheetFile,ctx);
},
cellRenderAfter:function(cell,postion,sheetFile,ctx){ // console.log(postion);
},
cellMousedownBefore:function(cell,postion,sheetFile,ctx){ // console.log(postion);
},
cellMousedown:function(cell,postion,sheetFile,ctx){ // console.log(sheetFile);
},
sheetMousemove:function(cell,postion,sheetFile,moveState,ctx){ // console.log(cell,postion,sheetFile,moveState,ctx);
},
sheetMouseup:function(cell,postion,sheetFile,moveState,ctx){ // console.log(cell,postion,sheetFile,moveState,ctx);
},
cellAllRenderBefore:function(data,sheetFile,ctx){ // console.info(data,sheetFile,ctx)
},
updated:function(operate){ // console.info(operate)
},
cellUpdateBefore:function(r,c,value,isRefresh){ // console.info('cellUpdateBefore',r,c,value,isRefresh)
},
cellUpdated:function(r,c,oldValue, newValue, isRefresh){ // console.info('cellUpdated',r,c,oldValue, newValue, isRefresh)
},
sheetActivate:function(index, isPivotInitial, isNewSheet){ // console.info(index, isPivotInitial, isNewSheet)
},
rangeSelect:function(index, sheet){ // console.info(index, sheet)
},
commentInsertBefore:function(r, c){ // console.info(r, c)
},
commentInsertAfter:function(r, c, cell){ // console.info(r, c, cell)
},
commentDeleteBefore:function(r, c, cell){ // console.info(r, c, cell)
},
commentDeleteAfter:function(r, c, cell){ // console.info(r, c, cell)
},
commentUpdateBefore:function(r, c, value){ // console.info(r, c, value)
},
commentUpdateAfter:function(r, c, oldCell, newCell ){
// console.info(r, c, oldCell, newCell)
},
cellEditBefore:function(range ){
// console.info(range)
},
workbookCreateAfter:function(json){
// console.info(json)
},
rangePasteBefore:function(range,data){ // console.info('rangePasteBefore',range,data) // return false; //Can intercept paste
},
},
//data:[
// {
// "name":"Sheet1",
// "config":{
// "columnlen":{
// "1":88,
// "2":76,
// "3":88,
// "4":69,
// "5":88,
// "6":69,
// "7":83,
// "8":62,
// "9":83,
// "10":55,
// "11":83,
// "12":62,
// "13":88,
// "14":76,
// "15":88,
// "16":69,
// "17":88,
// "18":69
// },
// "customWidth":{
// "1":1,
// "2":1,
// "3":1,
// "4":1,
// "5":1,
// "6":1,
// "7":1,
// "8":1,
// "9":1,
// "10":1,
// "11":1,
// "12":1,
// "13":1,
// "14":1,
// "15":1,
// "16":1,
// "17":1,
// "18":1
// },
// "borderInfo":[
// {
// "rangeType":"cell",
// "value":{
// "row_index":0,
// "col_index":0,
// "l":{
// "style":1,
// "color":"#302B2F"
// },
// "r":{
// "style":1,
// "color":"#302B2F"
// },
// "t":{
// "style":1,
// "color":"#302B2F"
// },
// "b":{
// "style":1,
// "color":"#302B2F"
// }
// }
// },
// {
// "rangeType":"cell",
// "value":{
// "row_index":0,
// "col_index":1,
// "l":{
// "style":1,
// "color":"#302B2F"
// },
// "r":{
// "style":1,
// "color":"#302B2F"
// },
// "t":{
// "style":1,
// "color":"#302B2F"
// },
// "b":{
// "style":1,
// "color":"#302B2F"
// }
// }
// },
// {
// "rangeType":"cell",
// "value":{
// "row_index":0,
// "col_index":2,
// "l":{
// "style":1,
// "color":"#302B2F"
// },
// "r":{
// "style":1,
// "color":"#302B2F"
// },
// "t":{
// "style":1,
// "color":"#302B2F"
// },
// "b":{
// "style":1,
// "color":"#302B2F"
// }
// }
// }
// ]
// }
// }
//]
}
}
luckysheet.create(options);
```
--------------------------------
### HTML Structure for CDN Integration
Source: https://context7.com/dream-num/luckyexcel/llms.txt
Includes necessary CSS and JS files for Luckysheet and Luckyexcel, along with input elements for file upload and a button to load a demo file. Initializes an empty Luckysheet instance.
```html
Excel Viewer
```
--------------------------------
### Initialize Luckysheet
Source: https://github.com/dream-num/luckyexcel/blob/master/dist/luckysheet/index.html
Configures and initializes the Luckysheet instance. Supports switching between collaborative mode and local mode based on URL parameters.
```javascript
$(function () { // According to the browser language var lang = luckysheetDemoUtil.language() === 'zh' ? 'zh' : 'en'; var isShare = luckysheetDemoUtil.getRequest().share; // '?share=1' opens the collaborative editing mode var gridKey = luckysheetDemoUtil.getRequest().gridKey; // workbook id for collaborative editing, or directly define here var options = null; if(isShare || gridKey){ // http://localhost:3000/?gridKey=12eyy789-kk45ofid-23737245 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{ // http://localhost:3000/ 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){ // console.log(rowNum); }, rowTitleCellRenderAfter:function(rowNum,postion,ctx){ // console.log(ctx); }, columnTitleCellRenderBefore:function(columnAbc,postion,ctx){ // console.log(columnAbc); }, columnTitleCellRenderAfter:function(columnAbc,postion,ctx){ // console.log(postion); }, cellRenderBefore:function(cell,postion,sheetFile,ctx){ // console.log(cell,postion,sheetFile,ctx); }, cellRenderAfter:function(cell,postion,sheetFile,ctx){ // console.log(postion); }, cellMousedownBefore:function(cell,postion,sheetFile,ctx){ // console.log(postion); }, cellMousedown:function(cell,postion,sheetFile,ctx){ // console.log(sheetFile); }, sheetMousemove:function(cell,postion,sheetFile,moveState,ctx){ // console.log(cell,postion,sheetFile,moveState,ctx); }, sheetMouseup:function(cell,postion,sheetFile,moveState,ctx){ // console.log(cell,postion,sheetFile,moveState,ctx); }, cellAllRenderBefore:function(data,sheetFile,ctx){ // console.info(data,sheetFile,ctx) }, updated:function(operate){ // console.info(operate) }, cellUpdateBefore:function(r,c,value,isRefresh){ // console.info('cellUpdateBefore',r,c,value,isRefresh) }, cellUpdated:function(r,c,oldValue, newValue, isRefresh){ // console.info('cellUpdated',r,c,oldValue, newValue, isRefresh) }, sheetActivate:function(index, isPivotInitial, isNewSheet){ // console.info(index, isPivotInitial, isNewSheet) }, rangeSelect:function(index, sheet){ // console.info(index, sheet) }, commentInsertBefore:function(r, c){ // console.info(r, c) }, commentInsertAfter:function(r, c, cell){ // console.info(r, c, cell) }, commentDeleteBefore:function(r, c, cell){ // console.info(r, c, cell) }, commentDeleteAfter:function(r, c, cell){ // console.info(r, c, cell) }, commentUpdateBefore:function(r, c, value){ // console.info(r, c, value) }, commentUpdateAfter:function(r, c, oldCell, newCell ){ // console.info(r, c, oldCell, newCell) }, cellEditBefore:function(range ){ // console.info(range) }, workbookCreateAfter:function(json){ // console.info(json) }, rangePasteBefore:function(range,data){ // console.info('rangePasteBefore',range,data) // return false; //Can intercept paste }, }, //data:[{"name":"Sheet1","config":{"columnlen":{"1":88,"2":76,"3":88,"4":69,"5":88,"6":69,"7":83,"8":62,"9":83,"10":55,"11":83,"12":62,"13":88,"14":76,"15":88,"16":69,"17":88,"18":69},"customWidth":{"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1},"borderInfo":[{"rangeType":"cell","value":{"row_index":0,"col_index":0,"l":{"style":1,"color":"#302B2F"},"r":{"style":1,"color":"#302B2F"},"t":{"style":1,"color":"#302B2F"},"b":{"style":1,"color":"#302B2F"}}},{"rangeType":"cell","value":{"row_index":0,"col_index":1,"l":{"style":1,"color":"#302B2F"},"r":{"style":1,"color":"#302B2F"},"t":{"style":1,"color":"#302B2F"},"b":{"style":1,"color":"#302B2F"}}},{"rangeType":"cell","value":{"row_index":0,"col_index":2,"l":{"style":1,"color":"#302B2F"},"r":{"style":1,"color":"#302B2F"},"t":{"style":1,"color":"#302B2F"},"b":{"style":1,"color":"#302B2F"}}}]
```
--------------------------------
### Initialize LuckySheet
Source: https://github.com/dream-num/luckyexcel/blob/master/src/index.html
Initializes the LuckySheet component with specified options. Ensure the container ID 'luckysheet' is present in your HTML.
```javascript
$(function () {
//Configuration item
var options = {
container: 'luckysheet',
//luckysheet is the container id
showinfobar: false,
}
luckysheet.create(options)
});
```
--------------------------------
### Convert Excel to Luckysheet format (CDN)
Source: https://github.com/dream-num/luckyexcel/blob/master/README.md
Use this method when integrating Luckyexcel via a CDN. Ensure the xlsx file is obtained first, then use the global `window.LuckyExcel` object to perform the conversion. The callback function receives the converted JSON data and Luckysheet file structure.
```html
```
--------------------------------
### Import Excel file from remote URL
Source: https://context7.com/dream-num/luckyexcel/llms.txt
Fetches and converts an Excel file from a specified URL. Useful for server-side or cloud-hosted file integration without user interaction.
```javascript
// Load Excel file from remote URL
const excelUrl = 'https://example.com/spreadsheets/report.xlsx';
const fileName = 'Monthly Report.xlsx';
// Show loading indicator
const loadingMask = document.getElementById('loading-mask');
loadingMask.style.display = 'flex';
LuckyExcel.transformExcelToLuckyByUrl(
excelUrl,
fileName,
function(exportJson, luckysheetfile) {
// Hide loading indicator
loadingMask.style.display = 'none';
if (exportJson.sheets == null || exportJson.sheets.length === 0) {
alert('Failed to parse Excel file');
return;
}
// Access file metadata
console.log('Creator:', exportJson.info.creator);
console.log('Last modified by:', exportJson.info.lastmodifiedby);
console.log('Created:', exportJson.info.createdTime);
console.log('Modified:', exportJson.info.modifiedTime);
console.log('Company:', exportJson.info.company);
// Process each sheet
exportJson.sheets.forEach(function(sheet, index) {
console.log('Sheet ' + index + ':', sheet.name);
console.log(' Rows:', sheet.row);
console.log(' Columns:', sheet.column);
console.log(' Cells:', sheet.celldata ? sheet.celldata.length : 0);
});
// Initialize Luckysheet
luckysheet.destroy();
luckysheet.create({
container: 'luckysheet',
showinfobar: false,
data: exportJson.sheets,
title: exportJson.info.name
});
},
function(error) {
loadingMask.style.display = 'none';
console.error('Failed to load Excel file:', error);
alert('Error loading file from URL');
}
);
```
--------------------------------
### Import and use Luckyexcel in ES modules
Source: https://github.com/dream-num/luckyexcel/blob/master/README.md
Import the LuckyExcel module and use its `transformExcelToLucky` method for converting Excel files. The function accepts the file data and callback functions for success and error handling.
```javascript
import LuckyExcel from 'luckyexcel'
// After getting the xlsx file
LuckyExcel.transformExcelToLucky(data,
function(exportJson, luckysheetfile){
// Get the worksheet data after conversion
},
function(error){
// handle error if any thrown
}
)
```
--------------------------------
### Import Excel file from browser input
Source: https://context7.com/dream-num/luckyexcel/llms.txt
Converts a local file object from an input element into Luckysheet data. Requires validation of the file extension before processing.
```javascript
// Browser usage with file input
const fileInput = document.getElementById('excel-upload');
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
// Validate file extension
const fileName = file.name;
const extension = fileName.split('.').pop().toLowerCase();
if (extension !== 'xlsx') {
console.error('Only .xlsx files are supported');
return;
}
LuckyExcel.transformExcelToLucky(
file,
function(exportJson, luckysheetfile) {
// exportJson contains parsed data
// exportJson.info: file metadata (name, creator, dates)
// exportJson.sheets: array of sheet data
if (exportJson.sheets == null || exportJson.sheets.length === 0) {
console.error('No sheets found in Excel file');
return;
}
// Initialize Luckysheet with imported data
luckysheet.destroy();
luckysheet.create({
container: 'luckysheet', // Container element ID
data: exportJson.sheets, // Sheet data array
title: exportJson.info.name, // Workbook title
userInfo: exportJson.info.creator // Creator info
});
console.log('Import successful!');
console.log('File name:', exportJson.info.name);
console.log('Sheets count:', exportJson.sheets.length);
console.log('Raw JSON:', luckysheetfile);
},
function(error) {
console.error('Import failed:', error.message);
}
);
});
```
--------------------------------
### Handle Excel File Upload and Transformation
Source: https://github.com/dream-num/luckyexcel/blob/master/src/index.html
Handles the change event for a file input to upload and transform an Excel (.xlsx) file into a LuckySheet compatible JSON format. It then updates the LuckySheet instance with the transformed data. Only supports .xlsx files.
```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 = () => {
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
});
});
});
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
});
});
});
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;
});
}
}
}
demoHandler();
```
--------------------------------
### Node.js Server-Side Usage
Source: https://context7.com/dream-num/luckyexcel/llms.txt
Use Luckyexcel in Node.js for server-side Excel conversion. Requires reading the file using 'fs' and providing callback functions for success and error handling.
```javascript
const fs = require('fs');
const LuckyExcel = require('luckyexcel');
// Read Excel file from filesystem
const filePath = './uploads/inventory.xlsx';
fs.readFile(filePath, function(err, data) {
if (err) {
console.error('Failed to read file:', err);
return;
}
LuckyExcel.transformExcelToLucky(
data,
function(exportJson, luckysheetfile) {
// Process the converted data
console.log('File converted successfully');
console.log('Workbook name:', exportJson.info.name);
// Save as JSON for later use
const outputPath = './output/inventory.json';
fs.writeFileSync(outputPath, luckysheetfile);
console.log('JSON saved to:', outputPath);
// Extract specific data
const firstSheet = exportJson.sheets[0];
console.log('First sheet:', firstSheet.name);
console.log('Total cells:', firstSheet.celldata.length);
// Process cells into a 2D array
const maxRow = firstSheet.row;
const maxCol = firstSheet.column;
const grid = Array(maxRow).fill(null).map(() => Array(maxCol).fill(null));
firstSheet.celldata.forEach(cell => {
const value = cell.v;
if (typeof value === 'object' && value !== null) {
grid[cell.r][cell.c] = value.m || value.v;
} else {
grid[cell.r][cell.c] = value;
}
});
// Output first 5 rows
console.log('First 5 rows:');
grid.slice(0, 5).forEach((row, i) => {
console.log(`Row ${i}:`, row.slice(0, 10).join(' | '));
});
},
function(error) {
console.error('Conversion failed:', error);
}
);
});
```
--------------------------------
### Read and convert Excel file in Node.js
Source: https://github.com/dream-num/luckyexcel/blob/master/README.md
Use Node.js's `fs` module to read an Excel file and then employ LuckyExcel's `transformExcelToLucky` method to convert it. This is suitable for server-side operations.
```javascript
var fs = require("fs");
var LuckyExcel = require('luckyexcel');
// Read an xlsx file
fs.readFile("House cleaning checklist.xlsx", function(err, data) {
if (err) throw err;
LuckyExcel.transformExcelToLucky(data, function(exportJson, luckysheetfile){
// Get the worksheet data after conversion
});
});
```
--------------------------------
### Export JSON Data Structure
Source: https://context7.com/dream-num/luckyexcel/llms.txt
This structure represents the output of the LuckyExcel transformation, containing file information and an array of sheet objects with their respective cell data and configurations.
```APIDOC
## Export JSON Data Structure
### Description
The export JSON structure is the standard output format for LuckyExcel transformations. It encapsulates all necessary data to render a spreadsheet in Luckysheet, including metadata, cell values, formatting, and sheet-specific configurations.
### Response Structure
- **info** (object) - File metadata including name, creator, timestamps, and version.
- **sheets** (array) - A collection of sheet objects containing:
- **name** (string) - Sheet tab name.
- **celldata** (array) - Array of cell objects with row (r), column (c), and value (v) properties.
- **config** (object) - Sheet-level configurations like merges, row/column dimensions, and hidden states.
- **freezen** (object) - Frozen pane settings.
- **calcChain** (array) - Formula calculation dependencies.
### Response Example
{
"info": {
"name": "Financial Report.xlsx",
"creator": "John Doe",
"createdTime": "2024-01-15T10:30:00Z"
},
"sheets": [
{
"name": "Sales Data",
"celldata": [
{
"r": 0,
"c": 0,
"v": { "v": "Revenue", "m": "Revenue" }
}
],
"config": {
"merge": { "0_0": { "r": 0, "c": 0, "rs": 2, "cs": 3 } }
}
}
]
}
```
--------------------------------
### LuckyExcel.transformExcelToLuckyByUrl
Source: https://context7.com/dream-num/luckyexcel/llms.txt
Fetches an Excel file from a given URL and converts it into Luckysheet-compatible JSON. This is useful for loading Excel files directly from a server or cloud storage.
```APIDOC
## LuckyExcel.transformExcelToLuckyByUrl
### Description
Fetches and converts an Excel file from a remote URL to Luckysheet format. This method is useful for loading Excel files from servers, CDNs, or cloud storage without requiring user file selection. The method handles the HTTP request, binary data processing, and conversion automatically.
### Method
`LuckyExcel.transformExcelToLuckyByUrl(excelUrl, fileName, successCallback, errorCallback)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **excelUrl** (string) - Required - The URL of the Excel file to fetch.
- **fileName** (string) - Required - The name to assign to the Excel file during processing.
- **successCallback** (function) - Required - A callback function that receives `exportJson` and `luckysheetfile` upon successful conversion.
- **errorCallback** (function) - Required - A callback function that receives an `error` object if the conversion fails.
### Request Example
```javascript
// Load Excel file from remote URL
const excelUrl = 'https://example.com/spreadsheets/report.xlsx';
const fileName = 'Monthly Report.xlsx';
// Show loading indicator
const loadingMask = document.getElementById('loading-mask');
loadingMask.style.display = 'flex';
LuckyExcel.transformExcelToLuckyByUrl(
excelUrl,
fileName,
function(exportJson, luckysheetfile) {
// Hide loading indicator
loadingMask.style.display = 'none';
if (exportJson.sheets == null || exportJson.sheets.length === 0) {
alert('Failed to parse Excel file');
return;
}
// Access file metadata
console.log('Creator:', exportJson.info.creator);
console.log('Last modified by:', exportJson.info.lastmodifiedby);
console.log('Created:', exportJson.info.createdTime);
console.log('Modified:', exportJson.info.modifiedTime);
console.log('Company:', exportJson.info.company);
// Process each sheet
exportJson.sheets.forEach(function(sheet, index) {
console.log('Sheet ' + index + ':', sheet.name);
console.log(' Rows:', sheet.row);
console.log(' Columns:', sheet.column);
console.log(' Cells:', sheet.celldata ? sheet.celldata.length : 0);
});
// Initialize Luckysheet
luckysheet.destroy();
luckysheet.create({
container: 'luckysheet',
showinfobar: false,
data: exportJson.sheets,
title: exportJson.info.name
});
},
function(error) {
loadingMask.style.display = 'none';
console.error('Failed to load Excel file:', error);
alert('Error loading file from URL');
}
);
```
### Response
#### Success Response (200)
- **exportJson** (object) - Contains the parsed Excel data in Luckysheet format.
- **info** (object) - File metadata (name, creator, dates).
- **sheets** (array) - Array of sheet data.
- **luckysheetfile** (object) - Raw parsed data from the Excel file.
#### Response Example
```json
{
"exportJson": {
"info": {
"name": "Monthly Report",
"creator": "Admin",
"lastmodifiedby": "Admin",
"createdTime": "2023-10-27T11:00:00Z",
"modifiedTime": "2023-10-27T11:15:00Z",
"company": "Example Corp"
},
"sheets": [
{
"name": "Sheet1",
"celldata": [
{
"r": 0,
"c": 0,
"v": {
"v": "Report Data",
"m": "Report Data"
}
}
]
}
]
},
"luckysheetfile": { ... } // Raw data structure
}
```
```
--------------------------------
### LuckyExcel.transformExcelToLucky
Source: https://context7.com/dream-num/luckyexcel/llms.txt
Converts a local Excel file (File object) into Luckysheet-compatible JSON. This method is ideal for browser-based applications where users upload .xlsx files.
```APIDOC
## LuckyExcel.transformExcelToLucky
### Description
Converts an Excel file (File object) to Luckysheet-compatible JSON format. This is the primary method for browser-based file imports where users upload .xlsx files through a file input element. The method handles unzipping the Excel file, parsing XML content, extracting styles, and converting everything to Luckysheet's data structure.
### Method
`LuckyExcel.transformExcelToLucky(file, successCallback, errorCallback)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **file** (File) - Required - The Excel file object to be converted.
- **successCallback** (function) - Required - A callback function that receives `exportJson` and `luckysheetfile` upon successful conversion.
- **errorCallback** (function) - Required - A callback function that receives an `error` object if the conversion fails.
### Request Example
```javascript
// Browser usage with file input
const fileInput = document.getElementById('excel-upload');
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
// Validate file extension
const fileName = file.name;
const extension = fileName.split('.').pop().toLowerCase();
if (extension !== 'xlsx') {
console.error('Only .xlsx files are supported');
return;
}
LuckyExcel.transformExcelToLucky(
file,
function(exportJson, luckysheetfile) {
// exportJson contains parsed data
// exportJson.info: file metadata (name, creator, dates)
// exportJson.sheets: array of sheet data
if (exportJson.sheets == null || exportJson.sheets.length === 0) {
console.error('No sheets found in Excel file');
return;
}
// Initialize Luckysheet with imported data
luckysheet.destroy();
luckysheet.create({
container: 'luckysheet', // Container element ID
data: exportJson.sheets, // Sheet data array
title: exportJson.info.name, // Workbook title
userInfo: exportJson.info.creator // Creator info
});
console.log('Import successful!');
console.log('File name:', exportJson.info.name);
console.log('Sheets count:', exportJson.sheets.length);
console.log('Raw JSON:', luckysheetfile);
},
function(error) {
console.error('Import failed:', error.message);
}
);
});
```
### Response
#### Success Response (200)
- **exportJson** (object) - Contains the parsed Excel data in Luckysheet format.
- **info** (object) - File metadata (name, creator, dates).
- **sheets** (array) - Array of sheet data.
- **luckysheetfile** (object) - Raw parsed data from the Excel file.
#### Response Example
```json
{
"exportJson": {
"info": {
"name": "Example Workbook",
"creator": "User Name",
"createdTime": "2023-10-27T10:00:00Z",
"modifiedTime": "2023-10-27T10:30:00Z"
},
"sheets": [
{
"name": "Sheet1",
"celldata": [
{
"r": 0,
"c": 0,
"v": {
"v": "Hello",
"m": "Hello"
}
}
]
}
]
},
"luckysheetfile": { ... } // Raw data structure
}
```
```