How to download search result to cvs or excel file

Question:
On runtime we want to download the query result to excel or csv file too

Wix Editor

What are you trying to achieve:
trying to download the district wise sheets

What have you already tried:
the code that i’m using to display result

import wixAnimations from 'wix-animations';
import wixData from 'wix-data';
import wixWindow from 'wix-window';
import wixLocation from 'wix-location';

const totalCount = 0;
const pageSize = 200; // Adjust the page size based on your needs
let currentPage = 1;
const pageSizeBig = 1000; // Adjust the page size based on your needs
let currentPageBig = 1;

$w.onReady(function () {
    $w("#IOCLlist").pagination = { "type": "pagination", "rowsPerPage": 20 };
    $w("#IOCLlist").refresh();

    $w("#ddstate").onChange(function () { //------------on change STATE
        $w("#dddistrict").value = undefined;
        createdistrict()
        $w("#imgupb").hide();
        //$w("#imgups").show();
        $w("#dddistrict").show();
        //count()
    });

    $w("#dddistrict").onChange(function () { //------------on change District
        $w("#imgups").hide();
        $w("#IOCLlist").expand();
        $w("#IOCLlist").refresh();
        // $w("#mcmarket").show();
        count()
        $w("#IOCLlist").show();
    });
})

function createdistrict() {
    wixData.query("IoclPetrolPump")
        .limit(pageSize)
        .skip((currentPage - 1) * pageSize)
        .contains("state", $w("#ddstate").value)
        .ascending("district")
        .distinct("district")
        .then(results => {
            const districtOptions = results.items.map(item => ({ label: item, value: item }));
            $w("#dddistrict").options = districtOptions;
        })
        .catch(error => {
            console.error("Error fetching districts:", error);
        });
}

function count() {
    let totalCount = 0;
    wixData.query("IoclPetrolPump")
        .contains("state", $w("#ddstate").value)
        .contains("district", $w("#dddistrict").value)
        .isNotEmpty("latitude")
        .isNotEmpty("longitude")
        .count()
        .then(totalCount => {
            console.log("Total Count:", totalCount);
            if (totalCount > 0) {
                $w("#test").text = "Total Records:- " + totalCount // Do something when there are records in the dataset
                $w("#test").show();
                tabledb();
            }
        })
}

function tabledb() {
    const selectedDistrict = $w("#dddistrict").value;
    wixData.query("IoclPetrolPump")
        .limit(pageSizeBig)
        .skip((currentPageBig - 1) * pageSizeBig)
        .contains("state", $w("#ddstate").value)
        .contains("district", $w("#dddistrict").value)
        .isNotEmpty("latitude")
        .isNotEmpty("longitude")
        .ascending("district")
        .ascending("city")
        .ascending("market")
        .ascending("location")
        .find()
        .then(results => {
            const fields = ["roCode", "city", "location", "category", "pumpName", "photo", "streetView"];
            const labels = ["Code", "City", "Address", "Category", "Pump Name", "Profile / Map", "Street View"];
            $w('#ddstate')
            const columns = fields.map((field, index) => ({
                "id": field,
                "dataPath": `rowItem.${field}`,
                "label": labels[index]

            }));

            $w("#IOCLlist").columns.values()
            // Create rows based on the fetched data
            const rows = results.items.map(item => {
                const row = {};
                fields.forEach(field => {

                    if (field === "streetView") {
                            row[field] = `<a href="${item[field]}" target="_blank">√</a>`;
                    } else {

                        if (field === "photo") {
                            row[field] = `<a href="${item[field]}" target="_blank">√</a>`;
                        } else {
                            // For fields other than "photo field"
                            row[field] = item[field] !== null ? item[field] : '';
                        }
                    }
                });
                return row;
            });
            $w("#IOCLlist").rows = rows;
        })
        .catch(error => {
            console.error("Error fetching data:", error);
        });
}

There’s probably two ways you can do this. Both would involve using the json-2-csv - npm library to turn your json results into CSV format.

Then you can do one of the following options:

  1. Use upload - Velo API Reference - Wix.com to store the data in the media manager and https://www.wix.com/velo/reference/wix-media-backend/mediamanager-obj/getdownloadurl to let the user download it. You might want to also schedule a job to occasionally delete old files.
  2. Avoid uploading the data to the media manager and instead generate the CSV by passing the data into an iframe that then has a download button to download the data locally: javascript - How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system? - Stack Overflow
    [Solved] how to download attachment using Iframe - CodeProject

For the second option it should work but I’ve not tried it.