ReactJs - xlsx: Add data to an existing excel file

29 views Asked by At

i have base64 string of template form excel, i want to add data into file excel and download it, i try with https://www.npmjs.com/package/xlsx but when fill data into excel file, font size, lineheight, line are disappear

Before: [1]: https://i.stack.imgur.com/2SEM3.png After: [2]: https://i.stack.imgur.com/cFlFe.png

function downloadExcelXLS(base64Template) {
  const data = [
    ['John', 25, 'Engineer'],
    ['Alice', 30, 'Manager'],
  ]
  const binaryString = atob(base64Template);

  const byteArray = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    byteArray[i] = binaryString.charCodeAt(i);
  }

  const workbook = XLSX.read(byteArray, { type: 'array' });

  // Access the first sheet
  const sheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[sheetName];

  // Assuming the template has placeholders starting from cell A1
  const range = XLSX.utils.decode_range(sheet['!ref']);

  // Write data into the template
  data.forEach((rowData, rowIndex) => {
    rowData.forEach((cellData, colIndex) => {
      const cellAddress = XLSX.utils.encode_cell({ r: rowIndex + range.s.r, c: colIndex + range.s.c });
      sheet[cellAddress] = { t: 's', v: cellData }; // Assuming all data are strings
    });
  });

  // Preserve formatting by copying styles from the original template
  const templateSheet = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { header: 1 });
  templateSheet.forEach((row, rowIndex) => {
    row.forEach((cell, colIndex) => {
      const cellAddress = XLSX.utils.encode_cell({ r: rowIndex, c: colIndex });
      if (cell !== undefined && sheet[cellAddress] !== undefined) {
        sheet[cellAddress].s = workbook.Sheets[sheetName][cellAddress].s;
      }
    });
  });

  const wbout = XLSX.write(workbook, { type: 'binary', bookType: 'xlsx' });

  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

  const url = URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'Schedule.xlsx');

  link.click();
}

// Convert string to array buffer
function s2ab(s) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff;
  return buf;
}

0

There are 0 answers