luckyexcel

repository·master·Indexed 19 days ago

https://github.com/dream-num/luckyexcel

An Excel import and export library designed to adapt .xlsx files for use with Luckysheet. It converts .xlsx files into a JSON format that Luckysheet can render, supporting cell styles, borders, formulas, and various cell formats. The library provides the transformExcelToLucky method for local files/buffers and transformExcelToLuckyByUrl for remote files.

Tokens
7K
Snippets
24
Records
33
Agent score
67%

What's inside luckyexcel

  1. Use luckyexcel via CDN

    master

    You can include luckyexcel directly in your HTML using a CDN script tag. The library will be available under the global window.LuckyExcel object.

    <script src="https://cdn.jsdelivr.net/npm/luckyexcel/dist/luckyexcel.umd.js"></script>
    <script>
        // 'file' is the obtained xlsx file
        LuckyExcel.transformExcelToLucky(
            file, 
            function(exportJson, luckysheetfile){
                // Initialize luckysheet with the converted data
                luckysheet.create({
                    container: 'luckysheet', 
                    data: exportJson.sheets,
                    title: exportJson.info.name,
                    userInfo: exportJson.info.name.creator
                });
            },
            function(err){
                console.error('Import failed. Is your file a valid xlsx?');
            });
    </script>
  2. Import Excel files via CDN

    master

    To use Luckyexcel in a browser environment without a module bundler, include the UMD build via JSDelivr. Use LuckyExcel.transformExcelToLucky to convert an .xlsx file into a format compatible with Luckysheet.

    Note: You must have Luckysheet already loaded and a container initialized to use the resulting data.

    <script src="https://cdn.jsdelivr.net/npm/luckyexcel/dist/luckyexcel.umd.js"></script>
    <script>
        // Ensure 'file' is a valid xlsx file object
        LuckyExcel.transformExcelToLucky(
            file, 
            function(exportJson, luckysheetfile){
                // Use the converted data to initialize or update Luckysheet
                luckysheet.create({
                    container: 'luckysheet', // luckysheet is the container id
                    data: exportJson.sheets,
                    title: exportJson.info.name,
                    userInfo: exportJson.info.name.creator
                });
            },
            function(err){
                console.error('Import failed. Is your file a valid xlsx?', err);
            }
        );
    </script>
  3. Understand the LuckySheetCelldata class

    master

    The LuckySheetCelldata class is a core component used to transform raw XML cell elements from an Excel file into a structured format compatible with LuckySheet. It handles the extraction of cell values, formulas, and complex styling information.

    When instantiated, it automatically processes the following:

    • Cell Coordinates: Extracts row (r) and column (c) indices.
    • Values: Resolves cell values from various sources including direct values, SharedString tables, or inlineStr types.
    • Formulas: Detects and formats formulas (e.g., prepending = to the formula string).
    • Styling: Maps Excel styles (fonts, fills, borders, alignment, and number formats) to the LuckySheetCelldataValue structure.
    • Rich Text: Handles inlineStr and complex text formatting (bold, italic, underline, font family, etc.) for individual characters or segments within a cell.
    // Note: The constructor is used internally by the parser to transform XML elements.
    // It requires several dependencies from the ReadXml process.
    new LuckySheetCelldata(
      cell: Element, 
      styles: IStyleCollections, 
      sharedStrings: Element[], 
      mergeCells: Element[], 
      sheetFile: string, 
      ReadXml: ReadXml
    );
  4. Convert .xlsx files to Luckysheet format using transformExcelToLucky

    master

    The core functionality of luckyexcel is the transformExcelToLucky method. It converts .xlsx files (note: .xls is not supported) into a JSON format compatible with Luckysheet.

    Note: This library only supports the .xlsx format.

    // Example using ES modules
    import LuckyExcel from 'luckyexcel'
    
    // 'data' should be the file content/buffer from an .xlsx file
    LuckyExcel.transformExcelToLucky(data, 
        function(exportJson, luckysheetfile){
            // exportJson contains the converted worksheet data
        },
        function(error){
            // handle error if conversion fails
        }
    )
  5. Use Luckyexcel in ES modules

    master

    Import LuckyExcel from the package and use transformExcelToLucky to process an .xlsx file. The method accepts a file object and two callbacks: a success callback providing the converted JSON and a failure callback for error handling.

    import LuckyExcel from 'luckyexcel'
    
    // 'file' is the obtained xlsx file
    LuckyExcel.transformExcelToLucky(
        file, 
        function(exportJson, luckysheetfile){
            // Handle converted worksheet data here
        },
        function(error){
            // Handle errors here
        }
    )
  6. Transform Excel to Luckysheet via transformExcelToLucky()

    master

    The core method of Luckyexcel. It converts .xlsx files into a JSON structure that Luckysheet can consume.

    Parameters:

    • file (File | Buffer): The source .xlsx file or buffer.
    • successCallback (Function): Called on success. Receives (exportJson, luckysheetfile).
      • exportJson: Contains sheets (the data) and info (metadata like name and creator).
      • luckysheetfile: Additional file-related data.
    • errorCallback (Function): Called on failure. Receives (error).
  7. Use Luckyexcel in Node.js

    master

    In a Node.js environment, use require to import the library. You can pass the raw buffer/data read from the file system (using fs) directly into transformExcelToLucky.

    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){
            // Handle converted worksheet data here
        });
    });
  8. Transform an Excel file from a URL using transformExcelToLuckyByUrl()

    master

    Use LuckyExcel.transformExcelToLuckyByUrl() to convert an Excel file located at a specific URL into Luckysheet-compatible JSON. This is useful for remote files where you don't have a local File object.

    Parameters:

    • url: The string URL of the .xlsx file.
    • name: The name to be associated with the file.
    • callBack (optional): A function called upon success. It receives:
      • files: An IuploadfileList object containing the parsed Excel data.
      • fs: A string representing the raw Luckysheet file content.
    • errorHandler (optional): A function called if an error occurs.
    LuckyExcel.transformExcelToLuckyByUrl(
      'https://example.com/sample.xlsx',
      'sample.xlsx',
      (exportJson, luckysheetfile) => {
        console.log('Parsed JSON:', exportJson);
      },
      (err) => {
        console.error('Error:', err);
      }
    );
  9. Transform an Excel file using transformExcelToLucky()

    master

    Use LuckyExcel.transformExcelToLucky() to convert an .xlsx file into a JSON format compatible with Luckysheet. This method accepts a File object (typically from an <input type="file"> element) and provides the resulting data via a callback.

    Parameters:

    • excelFile: The File object to be processed.
    • callback (optional): A function called upon success. It receives two arguments:
      • files: An IuploadfileList object containing the parsed Excel data (the exportJson).
      • fs: A string representing the raw Luckysheet file content.
    • errorHandler (optional): A function called if an error occurs during processing.
    LuckyExcel.transformExcelToLucky(
      excelFile, 
      (exportJson, luckysheetfile) => {
        console.log('Parsed JSON:', exportJson);
        console.log('Raw string:', luckysheetfile);
      },
      (err) => {
        console.error('Transformation failed:', err);
      }
    );
  10. Parse Excel files to JSON string with Parse()

    master

    The Parse() method is the main execution method for the conversion process. It performs the following steps:

    1. Calls getWorkBookInfo() to extract file metadata.
    2. Calls getSheetsFull() to parse all worksheets and their contents.
    3. Converts the internal LuckyFile object into a JSON string via toJsonString().

    The resulting JSON string follows the ILuckyFile interface, which is the standard format required by LuckySheet to render the spreadsheet.