Didem Durukan
Didem Durukan

Reputation: 29

XLSX styling in Javascript in HTML does not work

I am trying to create and style an XLSX sheet with javascript in my html file. I can create the XLSX sheet however I cannot style it.

Things I have tried:

  1. I was using <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/xlsx.full.min.js"></script>, with this script I can create the sheet but I cannot style it.
  2. Then I tried using <script src="dist/xlsx.bundle.js"></script>, from this link. This also did not work and the error I get with this one is the following: ReferenceError: XLSX is not defined
  3. I have also tried other scripts but they needed me to use "require().." to define the XLSX like this: const XLSX = require('sheetjs-style'') or with require('xlsx') , however it did not work since "require" is not supported in the browser. I also tried the approaches here but still no success.

Here is my code:

<script src="dist/xlsx.bundle.js"></script>

<script type="text/javascript">
function createExcel(file_name) {
              var exampleData = JSON.parse(document.getElementById('exampleData').textContent);
              console.log("exampleData: ", exampleData);
              var dataForExcel = [];

              
              for (var field in exampleData) {
                // some data operations that fills the data for excel using
                // dataForExcel.push(....)

                } 

               var worksheet = XLSX.utils.json_to_sheet(dataForExcel);

              // Wrap text in cells and adjust row heights for long text
              // Apply text wrapping and center alignment in cells
              dataForExcel.forEach(function(row, rowIndex) {
                var cellValue = row.my_row;
                var cellAddress = XLSX.utils.encode_cell({r: rowIndex, c: 0});
                
                worksheet[cellAddress] = {
                  v: cellValue, 
                  s: { 
                    alignment: { 
                      wrapText: true, // Enable text wrapping
                      horizontal: 'center' // Center text horizontally
                    }
                  }
                };
              });
              }
</script>

Upvotes: 0

Views: 102

Answers (0)

Related Questions