Search code examples
javascriptexcelvue.jsparsingclipboard

vue js - parsing data from clipbord (excel)


I'm trying to parse data that the user paste from an excel file. y code look like this :

onPastingContacts(e) {
  const pastedData = e.clipboardData.getData('Text');
  const allPastedFields = pastedData.split('\n').filter(el => el !== '');
  allPastedFields.forEach(el => {
    const field = el.split('\t');
    let element = {
      'field1': field[0]?.replace(/\r/g, ''),
      'field2': field[1]?.replace(/\r/g, ''),
      'field3': field[2]?.replace(/\r/g, ''),
      'field4': field[3]?.replace(/\r/g, ''),
      'field5': field[4]?.replace(/\r/g, ''),
      'field6': field[5]?.replace(/\r/g, '')
    };
    Object.keys(element).forEach((key) => (element[key] == null) && delete element[key]); // remove empty fields from object
    Data.push(element)
  });
  return {Data}
},

And it works well in general, The problem is if the file contains text with '\n' or '\t' it parses it as if it were a new line in the file (or if it \t a new cell).

for example, if I'm trying to paste this file :

enter image description here

if I print the pasted data its look like this :

523961234 "This is an example with new line "

and if I print the Data array its look like this :

[{field1: '523961234', field2: 'This is an example'},
{field1: 'with new line '}]

And I need that this will be the result:

[{field1: '523961234', field2: 'This is an example \n with new line '}]

I know why it's append , does anyone have an idea how I can parse in a way that its work?


Solution

  • I split by '\r\n'. and this work for me. the new lines inside the cell were just \n . this is my code :

    onPastingContacts(e) {
      const pastedData = e.clipboardData.getData('Text');
      const allPastedFields = pastedData.split('\r\n').filter(el => el !== '');
      allPastedFields.forEach(el => {
        const field = el.split('\t');
        let element = {
          'field1': field[0]?.replace(/\r/g, ''),
          'field2': field[1]?.replace(/\r/g, ''),
          'field3': field[2]?.replace(/\r/g, ''),
          'field4': field[3]?.replace(/\r/g, ''),
          'field5': field[4]?.replace(/\r/g, ''),
          'field6': field[5]?.replace(/\r/g, '')
        };
        Object.keys(element).forEach((key) => (element[key] == null) && delete element[key]); // remove empty fields from object
        Data.push(element)
      });
      return {Data}
    },