luckysheet二次开发

前言

Luckysheet没有导入导出功能,所以需要二开

一、Luckysheet是什么?

Luckysheet 是一个类似于 excel 的在线电子表格,功能强大、配置简单且完全开源。

二、二开步骤

1.下载源码

源码地址:GitHub - dream-num/Luckysheet: Luckysheet is an online spreadsheet like excel that is powerful, simple to configure, and completely open source.

 

npm install
npm install gulp -g
npm run dev

 2.修改源码

1.若想要删除顶部的logo,可以在源码的src\controllers\constant.js

2.导出功能(luckysheet源码有部分对导出功能,我是在这基础上改的)

源码地址在src\controllers\handler.js(源码上的导出功能需要通过与后端地址,我这边是改成通过插件导出,如果通过后端地址可以满足,那就不需要改)

使用exceljs插件导出(注意:exceljs版本用4.3.0,其它的可能有问题),源码地址在src\expendPlugins\exportXlsx\plugin.js


import locale from '../../locale/locale';
import { modelHTML } from "../../controllers/constant";
import { arrayRemoveItem, replaceHtml } from '../../utils/util';
import tooltip from '../../global/tooltip';
import { getSheetIndex } from '../../methods/get';
import Store from '../../store';

// Initialize the export xlsx api
function exportXlsx(options, config, isDemo) {
    arrayRemoveItem(Store.asyncLoad, 'exportXlsx')
}

function downloadXlsx(data, filename) {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.click();
    URL.revokeObjectURL(url);
}

/**
 * 
 * @param {*} url 
 * @param {*} success 
 * @param {*} fail 
 */
function fetchAndDownloadXlsx({ url, order }, success, fail) {
    const luckyJson = luckysheet.toJson();
    luckysheet.getAllChartsBase64((chartMap) => {
        luckyJson.chartMap = chartMap
        luckyJson.devicePixelRatio = window.devicePixelRatio
        luckyJson.exportXlsx = {
            order
        }
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(luckyJson)
        })
            .then((response) => response.blob())
            .then((blob) => {
                if (blob.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
                    const filename = luckyJson.title + '.xlsx';
                    downloadXlsx(blob, filename);
                    success && success()
                } else {
                    fail && fail()
                }

            })
            .catch((error) => {
                console.error('fetch error:', error);
                fail && fail()
            });
    })


}

function createExportDialog(luckysheetfile) {
    $("#luckysheet-modal-dialog-mask").hide();
    var xlsxContainer = $("#luckysheet-export-xlsx");

    if (xlsxContainer.length === 0) {

        const _locale = locale();
        const locale_exportXlsx = _locale.exportXlsx;
        const locale_button = _locale.button;

        let content = `<div class="luckysheet-export-xlsx-content" style="padding: 10px 10px 10px 0;">
                <span>${locale_exportXlsx.range}</span>
                <select class="luckysheet-export-xlsx-select-area">
                    <option value="allSheets" selected="selected">${locale_exportXlsx.allSheets}</option>
                    <option value="currentSheet">${locale_exportXlsx.currentSheet}</option>
                </select>
        </div>`;

        $("body").append(
            replaceHtml(modelHTML, {
                id: "luckysheet-export-xlsx",
                addclass: "luckysheet-export-xlsx",
                title: locale_exportXlsx.title,
                content: content,
                botton: `<button class="btn btn-primary luckysheet-model-confirm-btn">${locale_button.confirm}</button><button class="btn btn-default luckysheet-model-close-btn">${locale_button.close}</button>`,
                style: "z-index:991",
                close: locale_button.close,
            }),
        );

        selectedOption = 'allSheets'

        // init event
        $("#luckysheet-export-xlsx .luckysheet-model-confirm-btn").on('click', () => {
            luckysheet.showLoadingProgress()

            var order = 'all'
            if (selectedOption === 'currentSheet') {
                order = getSheetIndex(Store.currentSheetIndex)
            }
            if(order=='all'){
                exportExcelFront(luckysheetfile,"报表")
                luckysheet.hideLoadingProgress()
            }else{
                let arr=[]
                arr.push(luckysheetfile[order])
                exportExcelFront(arr,luckysheetfile[order].name)
                luckysheet.hideLoadingProgress()
            }
            // fetchAndDownloadXlsx({ url, order }, () => {
            //     luckysheet.hideLoadingProgress()
            // }, () => {
            //     luckysheet.hideLoadingProgress()
            //     tooltip.info(_locale.exportXlsx.serverError, "");
            // })
            
            $("#luckysheet-export-xlsx").hide()
        })

        $("#luckysheet-export-xlsx .luckysheet-export-xlsx-select-area").change(function () {
            selectedOption = $(this).val();
        });

    }



    let $t = $("#luckysheet-export-xlsx").find(".luckysheet-modal-dialog-content").css("min-width", 350).end(),
        myh = $t.outerHeight(),
        myw = $t.outerWidth();
    let winw = $(window).width(),
        winh = $(window).height();
    let scrollLeft = $(document).scrollLeft(),
        scrollTop = $(document).scrollTop();
    $("#luckysheet-export-xlsx")
        .css({ left: (winw + scrollLeft - myw) / 2, top: (winh + scrollTop - myh) / 3 })
        .show();

}


const ExcelJS = require('exceljs')

function exportExcelFront(luckysheet, name, excelType) {
    // 1.创建工作簿,可以为工作簿添加属性
    const workbook = new ExcelJS.Workbook()
    // 2.创建表格,第二个参数可以配置创建什么样的工作表
    luckysheet.forEach(function (table) {
        // debugger
        if (table.data.length === 0) return true
        const worksheet = workbook.addWorksheet(table.name)
        const merge = (table.config && table.config.merge) || {}        //合并单元格
        const borderInfo = (table.config && table.config.borderInfo) || {}      //边框
        const columnWidth = (table.config && table.config.columnlen) || {}    //列宽
        const rowHeight = (table.config && table.config.rowlen) || {}      //行高
        const frozen = table.frozen || {}       //冻结
        const rowhidden = (table.config && table.config.rowhidden) || {}    //行隐藏
        const colhidden = (table.config && table.config.colhidden) || {}    //列隐藏
        const filterSelect = table.filter_select || {}    //筛选
        const images = table.images || {}   //图片
        // console.log(table)
        const hide = table.hide;    //工作表 sheet 1隐藏
        if (hide === 1) {
            // 隐藏工作表
            worksheet.state = 'hidden';
        }
        setStyleAndValue(table.data, worksheet)
        setMerge(merge, worksheet)
        setBorder(borderInfo, worksheet)
        setImages(images, worksheet, workbook)
        setColumnWidth(columnWidth, worksheet)
        //行高设置50导出后在ms-excel中打开显示25,在wps-excel中打开显示50这个bug不会修复
        setRowHeight(rowHeight, worksheet, excelType)
        setFrozen(frozen, worksheet)
        setRowHidden(rowhidden, worksheet)
        setColHidden(colhidden, worksheet)
        setFilter(filterSelect, worksheet)
        return true
    })

    // 4.写入 buffer
    const buffer = workbook.xlsx.writeBuffer().then(data => {
        const blob = new Blob([data], {
            type: 'application/vnd.ms-excel;charset=utf-8'
        })
        // console.log("导出成功!")
        // saveAs(blob, `${name}.xlsx`)
        // 获取heads中的filename文件名
        let downloadElement = document.createElement("a");
        // 创建下载的链接
        let href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        // 下载后文件名
        downloadElement.download = `${name}.xlsx`;
        document.body.appendChild(downloadElement);
        // 点击下载
        downloadElement.click();
        // 下载完成移除元素
        document.body.removeChild(downloadElement);
        // 释放掉blob对象
        window.URL.revokeObjectURL(href);
    })
    return buffer
}

/**
 * 列宽
 * @param columnWidth
 * @param worksheet
 */
var setColumnWidth = function (columnWidth, worksheet) {
    for (let key in columnWidth) {
        worksheet.getColumn(parseInt(key) + 1).width = columnWidth[key] / 7.5
    }
}

/**
 * 行高
 * @param rowHeight
 * @param worksheet
 * @param excelType
 */
var setRowHeight = function (rowHeight, worksheet, excelType) {
    //导出的文件用wps打开和用excel打开显示的行高大一倍
    if (excelType == "wps") {
        for (let key in rowHeight) {
            worksheet.getRow(parseInt(key) + 1).height = rowHeight[key] * 0.75
        }
    }
    if (excelType == "office" || excelType == undefined) {
        for (let key in rowHeight) {
            worksheet.getRow(parseInt(key) + 1).height = rowHeight[key] * 1.5
        }
    }
}

/**
 * 合并单元格
 * @param luckyMerge
 * @param worksheet
 */
var setMerge = function (luckyMerge = {}, worksheet) {
    const mergearr = Object.values(luckyMerge)
    mergearr.forEach(function (elem) {
        // elem格式:{r: 0, c: 0, rs: 1, cs: 2}
        // 按开始行,开始列,结束行,结束列合并(相当于 K10:M12)
        worksheet.mergeCells(
            elem.r + 1,
            elem.c + 1,
            elem.r + elem.rs,
            elem.c + elem.cs
        )
    })
}

/**
 * 设置边框
 * @param luckyBorderInfo
 * @param worksheet
 */
var setBorder = function (luckyBorderInfo, worksheet) {
    if (!Array.isArray(luckyBorderInfo)) return

    //合并边框信息
    var mergeCellBorder = function (border1, border2) {
        if (undefined === border1 || Object.keys(border1).length === 0) return border2;
        return Object.assign({}, border1, border2)
    }

    // console.log('luckyBorderInfo', luckyBorderInfo)
    luckyBorderInfo.forEach(function (elem) {
        // 现在只兼容到borderType 为range的情况
        // console.log('ele', elem)
        if (elem.rangeType === 'range') {
            let border = borderConvert(elem.borderType, elem.style, elem.color)
            let rang = elem.range[0]
            let row = rang.row
            let column = rang.column

            let rowBegin = row[0]
            let rowEnd = row[1]
            let colBegin = column[0]
            let colEnd = column[1]
            //处理外边框的情况 没有直接对应的外边框 需要转换成上下左右
            if (border.all) {//全部边框
                let b = border.all
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                        let border = {}
                        border['top'] = b;
                        border['bottom'] = b;
                        border['left'] = b;
                        border['right'] = b;
                        worksheet.getCell(i, y).border = border
                        // console.log(i, y, worksheet.getCell(i, y).border)
                    }
                }
            } else if (border.top) {//上边框
                let b = border.top
                let i = row[0] + 1;
                for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                    let border = {}
                    border['top'] = b;
                    worksheet.getCell(i, y).border = border
                    // console.log(i, y, worksheet.getCell(i, y).border)
                }
            } else if (border.right) {//右边框
                let b = border.right
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    let y = column[1] + 1;
                    let border = {}
                    border['right'] = b;
                    worksheet.getCell(i, y).border = border
                    // console.log(i, y, worksheet.getCell(i, y).border)
                }
            } else if (border.bottom) {//下边框
                let b = border.bottom
                let i = row[1] + 1;
                for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                    let border = {}

                    border['bottom'] = b;
                    worksheet.getCell(i, y).border = border
                    // console.log(i, y, worksheet.getCell(i, y).border)
                }
            } else if (border.left) {//左边框
                let b = border.left
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    let y = column[0] + 1;
                    let border = {}
                    border['left'] = b;
                    worksheet.getCell(i, y).border = border
                    // console.log(i, y, worksheet.getCell(i, y).border)
                }
            } else if (border.outside) {//外边框
                let b = border.outside
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                        let border = {}
                        if (i === rowBegin + 1) {
                            border['top'] = b
                        }
                        if (i === rowEnd + 1) {
                            border['bottom'] = b
                        }
                        if (y === colBegin + 1) {
                            border['left'] = b
                        }
                        if (y === colEnd + 1) {
                            border['right'] = b
                        }
                        let border1 = worksheet.getCell(i, y).border
                        worksheet.getCell(i, y).border = mergeCellBorder(border1, border)
                        // console.log(i, y, worksheet.getCell(i, y).border)
                    }
                }
            } else if (border.inside) {//内边框
                let b = border.inside
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                        let border = {}
                        if (i !== rowBegin + 1) {
                            border['top'] = b
                        }
                        if (i !== rowEnd + 1) {
                            border['bottom'] = b
                        }
                        if (y !== colBegin + 1) {
                            border['left'] = b
                        }
                        if (y !== colEnd + 1) {
                            border['right'] = b
                        }
                        let border1 = worksheet.getCell(i, y).border
                        worksheet.getCell(i, y).border = mergeCellBorder(border1, border)
                        // console.log(i, y, worksheet.getCell(i, y).border)
                    }
                }
            } else if (border.horizontal) {//内侧水平边框
                let b = border.horizontal
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                        let border = {}
                        if (i === rowBegin + 1) {
                            border['bottom'] = b
                        } else if (i === rowEnd + 1) {
                            border['top'] = b
                        } else {
                            border['top'] = b
                            border['bottom'] = b
                        }
                        let border1 = worksheet.getCell(i, y).border
                        worksheet.getCell(i, y).border = mergeCellBorder(border1, border)
                        // console.log(i, y, worksheet.getCell(i, y).border)
                    }
                }
            } else if (border.vertical) {//内侧垂直边框
                let b = border.vertical
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                        let border = {}
                        if (y === colBegin + 1) {
                            border['right'] = b
                        } else if (y === colEnd + 1) {
                            border['left'] = b
                        } else {
                            border['left'] = b
                            border['right'] = b
                        }
                        let border1 = worksheet.getCell(i, y).border
                        worksheet.getCell(i, y).border = mergeCellBorder(border1, border)
                        // console.log(i, y, worksheet.getCell(i, y).border)
                    }
                }
            } else if (border.none) {//当luckysheet边框为border-none的时候表示没有边框 则将对应的单元格border清空
                for (let i = row[0] + 1; i <= row[1] + 1; i++) {
                    for (let y = column[0] + 1; y <= column[1] + 1; y++) {
                        worksheet.getCell(i, y).border = {}
                        // console.log(i, y, worksheet.getCell(i, y).border)
                    }
                }
            }
        }
        if (elem.rangeType === 'cell') {
            // col_index: 2
            // row_index: 1
            // b: {
            //   color: '#d0d4e3'
            //   style: 1
            // }
            const { col_index, row_index } = elem.value
            const borderData = Object.assign({}, elem.value)
            delete borderData.col_index
            delete borderData.row_index
            let border = addborderToCell(borderData, row_index, col_index)
            let border1 = worksheet.getCell(row_index + 1, col_index + 1).border;
            worksheet.getCell(row_index + 1, col_index + 1).border = mergeCellBorder(border1, border)
            // console.log(row_index + 1, col_index + 1, worksheet.getCell(row_index + 1, col_index + 1).border)
        }
    })
}


/**
 * 设置带样式的值
 * @param cellArr
 * @param worksheet
 */
var setStyleAndValue = function (cellArr, worksheet) {
    if (!Array.isArray(cellArr)) return
    cellArr.forEach(function (row, rowid) {
        row.every(function (cell, columnid) {
            if (!cell) return true
            let fill = fillConvert(cell.bg)

            let font = fontConvert(
                cell.ff,
                cell.fc,
                cell.bl,
                cell.it,
                cell.fs,
                cell.cl,
                cell.un
            )
            let alignment = alignmentConvert(cell.vt, cell.ht, cell.tb, cell.tr)
            let value = ''

            if (cell.f) {
                value = { formula: cell.f, result: cell.v }
            } else if (!cell.v && cell.ct && cell.ct.s) {
                // xls转为xlsx之后,内部存在不同的格式,都会进到富文本里,即值不存在与cell.v,而是存在于cell.ct.s之后
                let richText = [];
                let cts = cell.ct.s
                for (let i = 0; i < cts.length; i++) {
                    let rt = {
                        text: cts[i].v,
                        font: fontConvert(cts[i].ff, cts[i].fc, cts[i].bl, cts[i].it, cts[i].fs, cts[i].cl, cts[i].un)
                    }
                    richText.push(rt)
                }
                value = {
                    richText: richText
                };

            } else {
                //设置值为数字格式
                if (cell.v !== undefined && cell.v !== '') {
                    var v = +cell.v;
                    if (isNaN(v)) v = cell.v
                    value = v
                }
            }
            //  style 填入到_value中可以实现填充色
            let letter = createCellPos(columnid)
            let target = worksheet.getCell(letter + (rowid + 1))
            // console.log('1233', letter + (rowid + 1))
            for (const key in fill) {
                target.fill = fill
                break
            }
            target.font = font
            target.alignment = alignment
            target.value = value

            try {
                //设置单元格格式
                target.numFmt = cell.ct.fa;
            } catch (e) {
                console.warn(e)
            }

            return true
        })
    })
}

/**
 * 设置图片
 * @param images
 * @param worksheet
 * @param workbook
 */
var setImages = function (images, worksheet, workbook) {
    if (typeof images != "object") return;
    for (let key in images) {
        // console.log(images[key]);
        // "data:image/png;base64,iVBORw0KG..."
        // 通过 base64  将图像添加到工作簿
        const myBase64Image = images[key].src;
        //位置
        const tl = { col: images[key].default.left / 72, row: images[key].default.top / 19 }
        // 大小
        const ext = { width: images[key].default.width, height: images[key].default.height }
        const imageId = workbook.addImage({
            base64: myBase64Image,
            //extension: 'png',
        });
        worksheet.addImage(imageId, {
            tl: tl,
            ext: ext
        });
    }
}

/**
 * 冻结行列
 * @param frozen
 * @param worksheet
 */
var setFrozen = function (frozen = {}, worksheet) {
    switch (frozen.type) {
        // 冻结首行
        case 'row': {
            worksheet.views = [
                { state: 'frozen', xSplit: 0, ySplit: 1 }
            ];
            break
        }
        // 冻结首列
        case 'column': {
            worksheet.views = [
                { state: 'frozen', xSplit: 1, ySplit: 0 }
            ];
            break
        }
        // 冻结行列
        case 'both': {
            worksheet.views = [
                { state: 'frozen', xSplit: 1, ySplit: 1 }
            ];
            break
        }
        // 冻结行到选区
        case 'rangeRow': {
            let row = frozen.range.row_focus + 1
            worksheet.views = [
                { state: 'frozen', xSplit: 0, ySplit: row }
            ];
            break
        }
        // 冻结列到选区
        case 'rangeColumn': {
            let column = frozen.range.column_focus + 1
            worksheet.views = [
                { state: 'frozen', xSplit: column, ySplit: 0 }
            ];
            break
        }
        // 冻结行列到选区
        case 'rangeBoth': {
            let row = frozen.range.row_focus + 1
            let column = frozen.range.column_focus + 1
            worksheet.views = [
                { state: 'frozen', xSplit: column, ySplit: row }
            ];
        }

    }

}

/**
 * 行隐藏
 * @param rowhidden
 * @param worksheet
 */
var setRowHidden = function (rowhidden = {}, worksheet) {
    for (const key in rowhidden) {
        //如果当前行没有内容则隐藏不生效
        const row = worksheet.getRow(parseInt(key) + 1)
        row.hidden = true;
    }
}

/**
 * 列隐藏
 * @param colhidden
 * @param worksheet
 */
var setColHidden = function (colhidden = {}, worksheet) {
    for (const key in colhidden) {
        const column = worksheet.getColumn(parseInt(key) + 1)
        column.hidden = true;
    }
}

/**
 * 自动筛选器
 * @param filter
 * @param worksheet
 */
var setFilter = function (filter = {}, worksheet) {
    if (Object.keys(filter).length === 0) return
    const from = {
        row: filter.row[0] + 1,
        column: filter.column[0] + 1
    }

    const to = {
        row: filter.row[1] + 1,
        column: filter.column[1] + 1
    }

    worksheet.autoFilter = {
        from: from,
        to: to
    }

}

var fillConvert = function (bg) {
    if (!bg) {
        return {}
    }
    // const bgc = bg.replace('#', '')
    let fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: bg.startsWith("#") ? bg.replace('#', '') : colorRGBtoHex(bg).replace("#", "") },
    }
    return fill;
}

var fontConvert = function (
    ff = 0,
    fc = '#000000',
    bl = 0,
    it = 0,
    fs = 10,
    cl = 0,
    ul = 0
) {
    // luckysheet:ff(样式), fc(颜色), bl(粗体), it(斜体), fs(大小), cl(删除线), ul(下划线)
    const luckyToExcel = {
        0: '微软雅黑',
        1: '宋体(Song)',
        2: '黑体(ST Heiti)',
        3: '楷体(ST Kaiti)',
        4: '仿宋(ST FangSong)',
        5: '新宋体(ST Song)',
        6: '华文新魏',
        7: '华文行楷',
        8: '华文隶书',
        9: 'Arial',
        10: 'Times New Roman ',
        11: 'Tahoma ',
        12: 'Verdana',
        num2bl: function (num) {
            return num !== 0
        }
    }
    // 出现Bug,导入的时候ff为luckyToExcel的val

    let font = {
        name: typeof ff === 'number' ? luckyToExcel[ff] : ff,
        family: 1,
        size: fs,
        color: { argb: fc.startsWith("#") ? fc.replace('#', '') : colorRGBtoHex(fc).replace("#", "") },
        bold: luckyToExcel.num2bl(bl),
        italic: luckyToExcel.num2bl(it),
        underline: luckyToExcel.num2bl(ul),
        strike: luckyToExcel.num2bl(cl)
    }

    return font
}

var alignmentConvert = function (
    vt = 'default',
    ht = 'default',
    tb = 'default',
    tr = 'default'
) {
    // luckysheet:vt(垂直), ht(水平), tb(换行), tr(旋转)
    const luckyToExcel = {
        vertical: {
            0: 'middle',
            1: 'top',
            2: 'bottom',
            default: 'middle'
        },
        horizontal: {
            0: 'center',
            1: 'left',
            2: 'right',
            default: 'center'
        },
        wrapText: {
            0: false,
            1: false,
            2: true,
            default: false
        },
        textRotation: {
            0: 0,
            1: 45,
            2: -45,
            3: 'vertical',
            4: 90,
            5: -90,
            default: 0
        }
    }

    let alignment = {
        vertical: luckyToExcel.vertical[vt],
        horizontal: luckyToExcel.horizontal[ht],
        wrapText: luckyToExcel.wrapText[tb],
        textRotation: luckyToExcel.textRotation[tr]
    }
    return alignment
}

var borderConvert = function (borderType, style = 1, color = '#000') {
    // 对应luckysheet的config中borderinfo的的参数
    if (!borderType) {
        return {}
    }
    const luckyToExcel = {
        type: {
            'border-all': 'all',
            'border-top': 'top',
            'border-right': 'right',
            'border-bottom': 'bottom',
            'border-left': 'left',
            'border-outside': 'outside',
            'border-inside': 'inside',
            'border-horizontal': 'horizontal',
            'border-vertical': 'vertical',
            'border-none': 'none',
        },
        style: {
            0: 'none',
            1: 'thin',
            2: 'hair',
            3: 'dotted',
            4: 'dashDot', // 'Dashed',
            5: 'dashDot',
            6: 'dashDotDot',
            7: 'double',
            8: 'medium',
            9: 'mediumDashed',
            10: 'mediumDashDot',
            11: 'mediumDashDotDot',
            12: 'slantDashDot',
            13: 'thick'
        }
    }
    let border = {}
    border[luckyToExcel.type[borderType]] = {
        style: luckyToExcel.style[style],
        color: { argb: color.replace('#', '') }
    }
    return border
}

function addborderToCell(borders, row_index, col_index) {
    let border = {}
    const luckyExcel = {
        type: {
            l: 'left',
            r: 'right',
            b: 'bottom',
            t: 'top'
        },
        style: {
            0: 'none',
            1: 'thin',
            2: 'hair',
            3: 'dotted',
            4: 'dashDot', // 'Dashed',
            5: 'dashDot',
            6: 'dashDotDot',
            7: 'double',
            8: 'medium',
            9: 'mediumDashed',
            10: 'mediumDashDot',
            11: 'mediumDashDotDot',
            12: 'slantDashDot',
            13: 'thick'
        }
    }
    console.log('borders', borders)
    for (const bor in borders) {
        console.log(borders[bor])
        if (borders[bor] != null) {
            if (borders[bor].color.indexOf('rgb') === -1) {
                border[luckyExcel.type[bor]] = {
                    style: luckyExcel.style[borders[bor].style],
                    color: { argb: borders[bor].color.replace('#', '') }
                }
            } else {
                border[luckyExcel.type[bor]] = {
                    style: luckyExcel.style[borders[bor].style],
                    color: { argb: borders[bor].color }
                }
            }
        }

    }

    return border
}

function createCellPos(n) {
    let ordA = 'A'.charCodeAt(0)

    let ordZ = 'Z'.charCodeAt(0)
    let len = ordZ - ordA + 1
    let s = ''
    while (n >= 0) {
        s = String.fromCharCode((n % len) + ordA) + s

        n = Math.floor(n / len) - 1
    }
    return s
}

//rgb(255,255,255)转16进制 #ffffff
function colorRGBtoHex(color) {
    color = color.replace("rgb", "").replace("(", "").replace(")", "")
    var rgb = color.split(',');
    var r = parseInt(rgb[0]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2]);
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

export { exportXlsx, downloadXlsx, fetchAndDownloadXlsx, createExportDialog, exportExcelFront }

3.导入功能(源码没有导入功能相关,所以需要配置,importExcel是我命名的,可以自行修改)

a.在工具栏新增导入按钮,源码地址在src\controllers\toolbar.js

在defaultToolbar数组新增'importExcel',在toolbarIdMap对象中新增importExcel: '#luckysheet-icon-importExcel',在createToolbarHtml()函数中的htmlMap新增

 importExcel: `<div class="luckysheet-toolbar-button-split-left luckysheet-toolbar-button luckysheet-inline-block"
        data-tips="${toolbar.importExcel}" id="luckysheet-icon-importExcel" role="button" style="user-select: none;">
            <div class="luckysheet-toolbar-button-outer-box luckysheet-inline-block"
            style="user-select: none;">
                <div class="luckysheet-toolbar-menu-button-inner-box luckysheet-inline-block"
                style="user-select: none;">
                    <div class="luckysheet-toolbar-menu-button-caption luckysheet-inline-block"
                    style="user-select: none;">
                        <div class="luckysheet-icon luckysheet-inline-block " style="user-select: none;">
                            <div aria-hidden="true" class="luckysheet-icon-img-container luckysheet-icon-img luckysheet-icon-rotation-none "
                            style="user-select: none;">
                            <svg t="1713951707667" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7356" width="20" height="20"><path d="M895.7 796.2l1e-8-192c0-17.7-14.3-32-32.00000001-32s-32 14.3-32 32l0 192c0 17.7-14.3 32-32 32l-576 1e-8c-17.7 0-32-14.3-32-32.00000001l0-192c0-17.7-14.3-32-32-32s-32 14.3-32 32.00000001l0 191.99999999c0 52.89999999 43.1 95.99999999 96 96l576 0c52.89999999 0 95.99999999-43.1 96-96z" p-id="7357"></path><path d="M340.7 426.6c-11.6-11.7-30.7-11.7-42.4 0-11.7 11.6-11.7 30.7 0 42.4l191.5 191c6.2 6.2 14.4 9.1 22.6 8.7 8.1 0.4 16.4-2.5 22.6-8.7L725.90000001 468.4c11.7-11.6 11.7-30.7-1e-8-42.4-11.6-11.7-30.7-11.7-42.4 0l-144.3 145L539.2 158.3c0-16.5-13.5-30-30-30s-30 13.5-30 30l0 406.3-138.5-138z" p-id="7358"></path></svg>
                            <!--限制上传格式为xls和xslx-->
                             <input id="luckysheet-excelUpload" type="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="display:none;"></input>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>` // 'importExcel'

汉化,源码地址src\locale\zh.js,在toolbar新增importExcel: "导入",这样按钮就生成了

使用LuckyExcel插件导出,使用的版本是1.0.1,源码地址在src\controllers\menuButton.js

在menuButton中的initialMenuButton新增

  //importExcel
        $("#luckysheet-icon-importExcel").click(function () {
            $("#luckysheet-excelUpload").click();
        })
        $("#luckysheet-excelUpload").click(function (e) {
            e.stopPropagation();
        })
        $("#luckysheet-excelUpload").on("change", function (e) {
            let file = e.target.files;
            if (file == null || file.length == 0) {
                alert("文件为空,请重新选择文件");
                return;
            }
            let name = file[0].name;
            let suffixArr = name.split("."),
                suffix = suffixArr[suffixArr.length - 1];
            if (suffix != "xlsx") {
                alert("只支持xlsx文件,请重新选择");
                return;
            }
           
            luckysheet.destroy(); // 先销毁当前容器
            LuckyExcel.transformExcelToLucky(file[0], function(
              exportJson,
              luckysheetfile
            ) {
                console.log(exportJson)
              if (exportJson.sheets == null || exportJson.sheets.length == 0) {
                alert("读取excel文件内容失败,目前不支持xls文件!");
                return;
              }
              
              luckysheet.create({
                container: "luckysheet",
                showinfobar: false,
                data: exportJson.sheets,
                title: exportJson.info.name,
                userInfo: exportJson.info.name.creator
              });
            });
        })

 3.打包源码

npm run build

生成dist文件夹,如果是vue项目则将dist放置项目的public中,然后再通过index.html引入(我将dist文件名改成luckysheet)

总结 

以上内容是我根据其它途径以及自己项目需求实现的功能,有需要的可以参考参考!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值