How to Generate Excel Output in a Docly API Function Using JavaScript

One of the great features of Docly is its ability to generate various file types, including Excel, by writing simple JavaScript functions. By using a combination of JavaScript functions, we can create a table, fill it with data, and send it as an Excel file (XLSX).

Step 1: Creating a HTML Table

We start by creating an HTML table. Despite Excel and HTML being fundamentally different, Docly can interpret HTML tables and convert them to Xlsx. Which allows us to use them as a convenient method to structure our data. We create our table using JavaScript's write function:

// Write the table to the output buffer, which the htmlToXlsx will read from
write('<table>');
write('<tr><th>Column1</th><th>Column2</th></tr>'); // headers
write('<tr><td>Row1Value1</td><td>Row1Value2</td></tr>'); // row 1
write('<tr><td>Row2Value1</td><td>Row2Value2</td></tr>'); // row 2
write('</table>');

// Export the output buffer table to Xlsx
return docly.htmlToXlsx("Test.xlsx");

Step 2: Incorporating Dynamic Data

The previous example is a static HTML table. However, in a real-world scenario, you will likely want to use dynamic data. Let's incorporate that:

// Write the table to the output buffer, which the htmlToXlsx will read from
const data = [
    { Column1: 'Row1Value1', Column2: 'Row1Value2' },
    { Column1: 'Row2Value1', Column2: 'Row2Value2' },
    // more data...
];

write('<table>');

// Add the header row
write('<tr><th>Column1</th><th>Column2</th></tr>');

// Add the data rows
for (let row of data) {
    write(`<tr><td>${row.Column1}</td><td>${row.Column2}</td></tr>`);
}

write('</table>');

// Export the output buffer table to Xlsx
return docly.htmlToXlsx("Test.xlsx");

This function will now create an Excel file containing a table populated with our dynamic data. You might want to look into the docly functions listFiles, getFiles and/or getFolders to reteive data from Docly data storage.

Wrapping Up

In this blog post, we've explored the simplicity and power of generating Excel output in Docly using HTML tables and the docly.HtmlToXlsx function. With the automatic handling of conversions and MIME types by Docly, we can focus on what's essential: structuring and presenting our data effectively. This is yet another testament to Docly's commitment to streamlining API development and empowering developers to produce more with less effort, without compromising on quality.