To convert a JS file (containing data) to an Excel spreadsheet, you must parse the JavaScript object or array and use a library like SheetJS (xlsx) to write that data into a .xlsx file format. Since JavaScript files are code and not data tables, the process involves extracting the specific variable containing your information and triggering a browser download of a generated binary file.
What You'll Need
- A text editor (such as Visual Studio Code, Sublime Text, or Notepad++) to edit your JS files.
- A web browser to execute the script and download the resulting file.
- The SheetJS library (xlsx.full.min.js), which is the industry standard for creating Excel files in the browser.
- Basic knowledge of JavaScript arrays and objects.
Step-by-Step
- Prepare Your Data Source: Ensure the data in your JS file is structured as an array of objects. For example, if you have a file named
data.js, it should export a constant likeconst myData = [{ "Name": "John", "Age": 30 }, { "Name": "Jane", "Age": 25 }];. If the data is just a raw string or a complex nested object, you will need to flatten it into a table-like structure first. - Set Up Your HTML File: Create a basic HTML page to act as the interface for the conversion. Include a button that the user will click to trigger the export. This is necessary because browsers generally block automatic file downloads for security reasons; a user-initiated click event is required.
- Import the SheetJS Library: Add the SheetJS script to your HTML file. You can use a CDN link in a
<script>tag. This library provides theXLSXobject, which contains all the methods needed to convert JSON data into a workbook and then into a downloadable file. - Link Your JS Data File: Add a
<script>tag to your HTML that points to yourdata.jsfile. Make sure the data file is loaded before the script that handles the conversion. If you are using ES6 modules, useimport { myData } from './data.js'and set the script type tomodule. - Write the Conversion Function: Create a JavaScript function that performs the following logic:
- Call
XLSX.utils.json_to_sheet(myData). This method takes your array of objects and automatically creates a worksheet where the object keys become the column headers and the values become the rows. - Create a new workbook using
XLSX.utils.book_new(). - Append the worksheet to the workbook using
XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1").
- Call
- Trigger the Download: Use the
XLSX.writeFile(workbook, "filename.xlsx")method. This command tells the browser to package the workbook as a binary file and prompt the user to save it to their local drive. - Test the Execution: Open the HTML file in a browser, click your export button, and verify that the .xlsx file opens in Microsoft Excel or Google Sheets with the correct columns and rows.
Common Mistakes
One of the most frequent errors is attempting to export a JavaScript file directly without parsing the data. A .js file is a script, not a data format like JSON or CSV. If you try to upload a .js file into Excel via the "Import" menu, Excel will treat it as a text file and display the code (e.g., ) rather than the actual values. You must execute the code to access the variable.
Another common mistake is using inconsistent keys in your array of objects. SheetJS relies on the keys of the first object to determine the columns. If your first object is { "Name": "John" } but your second object is { "Full Name": "Jane" }, the library may create two separate columns or leave gaps in the data. Ensure every object in your array uses the exact same key names.
Many developers also forget to handle large datasets. Attempting to convert a JS array with tens of thousands of rows directly in the browser can freeze the UI thread, causing the browser to stop responding. For extremely large files, you should process the data in chunks or move the conversion logic to a Node.js backend using the same SheetJS library.
Tips
To make your Excel file look professional, avoid using the default json_to_sheet method if you need custom headers. Instead, create a separate array for your headers and use XLSX.utils.aoa_to_sheet (Array of Arrays). This allows you to name your columns "Customer Name" instead of the variable name "cust_nm".
If you are working with dates, remember that JavaScript Date objects can sometimes be converted to strings in a way that Excel doesn't recognize as a date. It is often safer to format your dates as ISO strings (YYYY-MM-DD) before passing the array to the SheetJS function to ensure Excel's date-sorting features work correctly.
For better performance, consider using a Web Worker. By moving the XLSX processing to a background thread, your website remains responsive while the browser calculates the binary structure of the spreadsheet, which is especially helpful for files exceeding 5,000 rows.
Troubleshooting
If the file does not download when you click the button, first check the browser console (F12 > Console). If you see XLSX is not defined, your library script is not loading correctly. Check the path to your CDN or local file and ensure the script tag is placed before your custom logic.
If the downloaded file is corrupted or cannot be opened by Excel, check if you are accidentally saving the file as a .txt or .js instead of .xlsx. Ensure the writeFile method has the correct extension. Additionally, verify that your data array is not empty; attempting to create a workbook from an empty array can sometimes result in an invalid file structure.
If the data appears in the wrong columns, inspect your JS object keys. JavaScript objects are not guaranteed to maintain order in older environments. To fix this, you can explicitly define the order of columns using the header option in json_to_sheet, passing an array of keys in the specific order you want them to appear in the spreadsheet.
If you encounter a "Cross-Origin Request Blocked" (CORS) error when loading your JS file, it is likely because you are opening the HTML file directly from your folder (file:// protocol). Use a local development server (like Live Server in VS Code) to serve the files via http://, which allows the browser to load the external JS data file securely.
Frequently Asked Questions
Can I convert a JS file to Excel without writing code?
Not directly, because a .js file is a script. You would first need to convert the JS data into a JSON file or CSV file using a converter, and then open that CSV in Excel. If the data is embedded in code, a script is required to extract it.
Does this method work for very large JS files?
It works for moderate sizes, but browser memory limits apply. For files larger than 10MB of raw JS data, it is recommended to use a Node.js script to perform the conversion on the server side to avoid crashing the user's browser.
Is SheetJS free to use?
SheetJS offers a community edition that is open-source and free for most basic export tasks. For advanced features like cell styling, formulas, and professional support, they offer a paid Pro version.
Can I add colors and bold text to the Excel cells?
The community version of SheetJS focuses on data and structure. To add styles like background colors, bold fonts, or merged cells, you will need the Pro version of SheetJS or an alternative library like ExcelJS.
Will this work on mobile browsers?
Yes, the SheetJS library works in all modern mobile browsers. The writeFile method triggers the standard mobile download prompt, allowing users to save the .xlsx file to their device storage.
What is the difference between CSV and XLSX for JS exports?
CSV is a simple text file that is easier to generate but doesn't support multiple sheets, formulas, or formatting. XLSX is a full binary spreadsheet format that supports multiple tabs and advanced Excel features.