CSV files are an essential part of computer science when you work with websites and databases. There might be some cases when the user has some data in the browser that you want to let them download this data. In that case, CSV files help the programmer to use them to download the website data in tabular form. Programmers use the CSV file format for the users to download the website data.
How can you download the CSV file?
This chapter will show you how you can download a CSV file from a client and the server.
Why needs CSV file?
Following example is one of the simplest examples of this chapter to create and download a CSV file.
To create the data for your CSV file, you just need to create a multi-dimensional array that will contain the data for the HTML page. You can create data manually for learning purpose instead of taking it from the HTML page directly.
See the code implementation to create and download the CSV file.
Create and download CSV file
In this example, we will create a multi-dimensional array and add some data to create a CSV file. Besides this, we will add a button to download this data by the user. When the user clicks on the given button, the data will start downloading in .csv file format.
Copy CodeTest it Now
Try to execute the above code on the web and get the output as shown in the below screenshot:
Click on this Download CSV button to download the CSV data created in this file and this CSV data will display on the web as well.
Open the downloaded CSV File
Look at the extension of the downloaded file, which will be .csv. For reference, open in the download CSV file in MS-Excel and see the data inside it. We will show you the output on both excel and notepad after opening the CSV file. You can see that CSV file data will show in tabular form.
See the below screenshot on MS-Excel of CSV data. Other than this, you have seen that we have also displayed the CSV data on the web browser.
CSV file on MS-Excel
CSV file on Notepad
Export and download the HTML table data of webpage into CSV file
In the following example, we will export the HTML table data from the webpage to a CSV file and download this CSV file. We will add a button to download this CSV data file on a single click of the user. When the user clicks on this button, the data will start downloading in .csv file format.
Copy CodeTest it Now
Copy and save the above code in a file and execute it on the web. You will get the output as given below in the screenshot on the web browser having an HTML table containing rows of data:
Click on the given Export to HTML table to CSV File button to download the data to CSV file format. The file will download by the name of person.csv.
You can open this file in MS-Excel to see the data contained inside it. Open the downloaded file and see the content present inside it same as the web HTML table content.