Export data collection to XLS excel file using code

Hi everyone,
here is a tutorial for how to export data collection to excel file using code.

To use this tutorial you need:

  1. Install the package: “xlsx”
  2. Button element
  3. html element
  4. web module - I called it excel.jsw

After installing the xlsx package, use this code for each element:

excel.jsw

const XLSX = require('xlsx'); 

export function exportExcel(worksheet) {
 var wb = XLSX.utils.book_new();
 var ws_name = "SheetJS";
 /* make worksheet */
 var ws_data = worksheet;
 var ws = XLSX.utils.aoa_to_sheet(ws_data);

 /* Add the worksheet to the workbook */
    XLSX.utils.book_append_sheet(wb, ws, ws_name);

return wb;
}

export function createAoA(rowNum,colNum) { //crete array of array for the excel export
 var x = new Array(rowNum);
for (var i = 0; i < x.length; i++) {
  x[i] = new Array(colNum);
 for (var j = 0; j < colNum; j++) {
      x[i][j]=0;
  }
}
return x;
}

Button element (I called it iconButton2) - this is the code for the web page

import { exportExcel } from 'backend/excel';
import { createAoA } from 'backend/excel';
import wixData from 'wix-data';

$w.onReady(function () {
 // TODO: write your page related code here...

});

export async function iconButton2_click(event) {

    wixData.query("payments") //change "payments" to your own collection name
        .find()
        .then((results) => {
 if (results.items.length > 0) {
                console.log(results);
 let colNum = Object.keys(results.items[0]).length;
 let rowsNum = results.items.length;
                createAoA(rowsNum, colNum).then(result2 => {
 for (var i = 0; i < rowsNum; i++) {
                        result2[i] = Object.values(results.items[i]);
                    }
                    console.log(result2, "result 2");
                    exportExcel(result2).then((excelfile) => {
                        console.log(excelfile, "excelfile");
                        $w('#html1').postMessage(excelfile);
                    })
                });
            } else {
                console.log("can't fint items");
            }
        })
        .catch((err) => {
 let errorMsg = err;
        });
}

html element

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.7/xlsx.js" integrity="sha512-fH2nbzuBSxkg1hpGKgSGlTcI5GQuqzaPTg04xY/W7UE6X8I+UENvr6qrlvX/G2NK7+acVkBznP1qefpMvNfP7A==" crossorigin="anonymous"></script>
</head>
<body>
<script>
var wb = XLSX.utils.book_new();
 var ws_name = "SheetJS";
 /* make worksheet */
 var ws_data = [
        ["S", "h", "e", "e", "t", "J", "S"],
        [1, 2, 3, 4, 5],
    [5,4,3,2,1]
    ];
 var ws = XLSX.utils.aoa_to_sheet(ws_data);

 
 /* Add the worksheet to the workbook */
    XLSX.utils.book_append_sheet(wb, ws, ws_name);
console.log(wb);
function myFunction(filewb) {
    XLSX.writeFile(filewb, 'out.xls');
}

window.onmessage = function(event){

 if (event.data) {
      wb = event.data;
      console.log(wb,"wb");
    }
 else {
      console.log("if error");

    }
  };
</script>

<button onclick="myFunction(wb)">export to excel</button>
</body>
</html>

let me know if you have any questions.
Enjoy :slight_smile: :sunglasses:

12 Likes

Great! Thanks a lot.
I’ll check it and

Thanks a lot.
Is there a way to import data from an Excel file to a collection using a code?

Just wonder can Wix Corvid Code could read Unicode Ramdom Binary into Wix Collection/Database

const XLSX = require('xlsx'); 

This creates an error
require
He does not recognize it
I would love your help this is really an important thing

I see he has indeed collected all the data great, but when I click on download, he downloads a file with some numbers 1 2 3 4 5 and that is without the content. Maybe because of the glitch I wrote earlier

In the end worked great! Despite the glitch.
a big thanks!!!
If there is a way to skip the second button it’s great!

Does not work. again. Would appreciate help.

It’s ok. just ignore it

Did you figure it out?

hello ziv! this is great, is what i need for a project but the Html component does not export the file. Following the steps I installed the xlsx npm package then create the backend file where i have a little error:

const XLSX = require('xlsx'); //require is not defined 

then I paste the code for the web page and the code for the Html component.
When I click the button on the page “iconButton2” I do get the console logs but when I click the “export to excel” button nothing happens

Hi,
just ignore the require error.
Can you share the link for this page? I will try to see what is wrong

1 Like

@zivassor Sure this is the link of the test page:
https://blinkcompany.wixsite.com/logistica/generarreporte

or you need the url of the page in the editor?

Hi,
it works perfectly here

Hi @zivassor !

Congrats on your solution for this problem. Beautiful!

It worked for me, but I made little changes to export a customized array, instead of the raw collection fields. I did this by suppressing the “.items” when using “results” from the query. Also worked… but…

I am struggling a little with empty cells. The exported Excel file ended mixing up the columns, filling the blanks with data from the next data column. It seems that this problem also occurs with the original code.

Also, I am just figuring out how to insert a header for the columns in the Excel file…

Thanks!

Hi @contato87032 ,
about the empty cells, in the " Button element (I called it iconButton2)" replace this code

result2[i] = Object.values(results.items[i]);

with this

result2[i] = [results.items[i].first_col, results.items[I].sec_col, etc...];

make sure you to write all columns you need (In case you too many, you can use a loop for this).

About the header, in the “Button element (I called it iconButton2)”, replace this code

createAoA(rowsNum, colNum).then(result2 => {
 for (var i = 0; i < rowsNum; i++) {
                        result2[i] = Object.values(results.items[i]);
                    }

with this

createAoA(rowsNum, colNum).then(result2 => {
result2[0] = [col_1, col_2, col_3, etc...];
 for (var i = 0; i < rowsNum; i++) {
                        result2[i+1] = Object.values(results.items[i]);
                    }

please let me know if you have any questions

1 Like

Hello @zivassor !
Thanks for the reply.
Concerning empty cells, I ended up filling them with “zero” in the dataset, it worked, but I will also try your solution.
About the header, since I am not using the dataset fields directly, but I am building a customized matrix, I realized that it would be easier to make this little changes in the function in backend that builds this matrix. It also worked.
Thanks again!

1 Like

Could be very useful for my project :sunglasses: THX!

1 Like

Hi @zivassor ,

I’m wondering if it would be possible to use something similar to export each new item submitted to a data collection when the item is added to the collection (via an on-site form etc.) and be exported in a new row/column to a pre-existing file…

For example, an excel file already exists collecting name; phone; address etc. and then when a new item is added to the corresponding collection in wix - that item is then exported as a new entry into the excel file.

Is there also a way to make this work with google sheets rather than excel?

I’m fairly new to using wix code, any help appreciated!

Hi @lisamthorpe ,
Sounds like the best way to do what you are asking for is using google sheet API.
You can see here how to do that.

good luck!

1 Like