vue-excel-editor icon indicating copy to clipboard operation
vue-excel-editor copied to clipboard

Paste from excel - an example

Open suspiciousfellow opened this issue 1 year ago • 1 comments

This isn't really an "issue", but I thought I would provide some sample code in a wrapper component I have written on how to do paste from excel. This could easily be adapted into the actual component. You would want to handle non text columns if your use case needs them (mine doesn't)

      <vue-excel-editor
        ...
        v-model="rows"
        @hook:mounted="removeListener"
        @paste.native.prevent="paste"
        ref="editor"
      >
        removeListener() {
            //this relies on the way that child component sets up paste handler
            //and therefore an upgrade to it may not work
            window.removeEventListener('paste', this.$refs.editor.winPaste);
        },
        paste(event) {
            let htmlPasteSuccess = false;
            const container = (new DOMParser ()).parseFromString(
                event.clipboardData.getData('text/html'),
                'text/html'
            );
            const newRows = [];
            container.querySelectorAll('tr').forEach((rowHtml, rowIndex) => {
                htmlPasteSuccess = true;
                const newRow = this.rows[rowIndex + this.$refs.editor.currentRowPos] ?? {};
                const cols = rowHtml.querySelectorAll('td');
                this.columns.forEach(({field}, colIndex) => {
                    colIndex -= this.$refs.editor.currentColPos;
                    if (colIndex in cols) {
                        newRow[field] = cols[colIndex].innerText;
                    } else {
                        newRow[field] = '';
                    }
                });
                newRows.push(newRow);
            });
            if (!htmlPasteSuccess) {
                this.$refs.editor.winPaste(event);
            } else {
                this.rows = this.rows.toSpliced(this.$refs.editor.currentRowPos, 0, ...newRows);
            }
        }

suspiciousfellow avatar Feb 06 '24 16:02 suspiciousfellow

Thank you, this gave me some clues to know how to process on my side

AloneInMyMind avatar Apr 12 '24 16:04 AloneInMyMind