Skip to main content

How to create a CSV file using Javascript (client and server side)

You can create a CSV file using JavaScript by doing the following:

1. Define your data: Create an array of arrays, where each inner array represents a row of data, with each element representing a column.

const data = [  ['Name', 'Age', 'Gender'],
  ['John', 25, 'Male'],
  ['Jane', 30, 'Female'],
  ['Bob', 35, 'Male'],
];

2. Convert the data to CSV format: Iterate over the data array and convert each row to a CSV string using join() method.

const csvRows = [];
data.forEach(row => {
  const csvRow = row.join(',');
  csvRows.push(csvRow);
});
const csvData = csvRows.join('\n');
3. Create and download the CSV file: Create a Blob object from the CSV data and create a URL from the Blob using URL.createObjectURL(). Then create a link and set the download attribute to the filename of the CSV file.
const blob = new Blob([csvData], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', 'data.csv');
link.click();
When the link is clicked, the browser will download the CSV file with the filename 'data.csv' containing the data in the specified format.

Note: This approach uses the client-side file download technique which requires the user's interaction with the browser. Server-side approaches can also be used to generate CSV files.

The code for generating a CSV file on the server side depends on the server-side technology that you are using. Here is an example using Node.js:

const fs = require('fs');
const data = [
  ['Name', 'Age', 'Gender'],
  ['John', 25, 'Male'],
  ['Jane', 30, 'Female'],
  ['Bob', 35, 'Male'],
];
const csvRows = [];
data.forEach(row => {
  const csvRow = row.join(',');
  csvRows.push(csvRow);
});
const csvData = csvRows.join('\n');
fs.writeFile('data.csv', csvData, (err) => {
  if (err) throw err;
  console.log('CSV file saved successfully');
});

In this example, we use the built-in fs module of Node.js to write the CSV data to a file called 'data.csv' in the current directory. We iterate over the data array and convert each row to a CSV string, then join all the rows with newline characters to create the final CSV data. We use the writeFile() method to write the data to the file, and handle any errors that may occur. Once the file is saved, a success message is logged to the console.

Comments

Popular posts from this blog

Learn how to setup push notifications in your Ionic app and send a sample notification using Node.js and PHP.

Ionic is an open source mobile UI toolkit for building modern, high quality cross-platform mobile apps from a single code base. To set up push notifications in your Ionic app, you will need to perform the following steps: Create a new Firebase project or use an existing one, and then enable Firebase Cloud Messaging (FCM) for your project. Install the Firebase Cloud Messaging plugin for Ionic: npm install @ionic-native/firebase-x --save Add the plugin to your app's app.module.ts file: import { FirebaseX } from '@ionic-native/firebase-x/ngx' ; @ NgModule({ ... providers: [ ... FirebaseX ... ] ... }) Initialize Firebase in your app's app.component.ts file: import { FirebaseX } from '@ionic-native/firebase-x/ngx' ; @ Component({ ... }) export class AppComponent { constructor ( private firebase : FirebaseX ) { this .firebase.init(); } } Register your app with Firebase Cloud Messaging by adding

How to export php/html page to Excel,Word & CSV file format

This class can generate the necessary request headers to make the outputted HTML be downloaded as a file by the browser with a file name that makes the file readable by Excel(.xls),Word(.doc) and CSV(.csv). Step1: Create PHP file named 'ExportPHP.class.php' ExportPHP.class.php <?php class ExportPHP { // method for Excel file function setHeaderXLS ( $file_name ) { header( "Content-type: application/ms-excel" ); header( "Content-Disposition: attachment; filename=$file_name" ); header( "Pragma: no-cache" ); header( "Expires: 0" ); } // method for Doc file function setHeaderDoc ( $file_name ) { header( "Content-type: application/x-ms-download" ); header( "Content-Disposition: attachment; filename=$file_name" ); header( 'Cache-Control: public' ); } // method for CSV file function setHeaderCSV (

Why is Apollo Client a crucial tool for your GraphQL project?

Apollo Client is a popular JavaScript library for managing GraphQL queries and mutations in client-side applications. There are several reasons why you might want to use Apollo Client in your GraphQL application: Simplified data management : With Apollo Client, you can easily manage your application's data with a single, declarative API. This can help to simplify your code and make it easier to reason about. Real-time updates : Apollo Client includes built-in support for subscriptions, which allow you to receive real-time updates from your GraphQL server. This can be useful for applications that require real-time data, such as chat applications or real-time analytics dashboards. Caching and performance : Apollo Client includes a sophisticated caching system that can help to improve the performance of your application by reducing the number of network requests required to fetch data. The cache can also be configured to automatically invalidate data when it becomes stale, ensuring th