Javascript чтение файла csv

Read CSV file in Javascript and HTML5 FileReader (Multiple ways)

If you are looking to get a solution to parse CSV using Javascript and show CSV file data into HTML table, then you can do it using plain javascript and HTML5 FileReader. Before we begin, you can understand, a comma-separated values (CSV) file is a delimited text file that uses a comma to separate values, so in this coding sample, a CSV file will be selected in HTML5 FileUpload element and will be read using HTML5 FileReader API, then the data will be parsed and showed into HTML table

Let’s begin by creating a HTML code to upload a file and call Javascript to parse CSV file.

I have also added empty div with to show data in it.

Now, let’s create the JS function to parse it

function processFile() < var fileSize = 0; //get file var theFile = document.getElementById("myFile"); var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/; //check if file is CSV if (regex.test(theFile.value.toLowerCase())) < //check if browser support FileReader if (typeof (FileReader) != "undefined") < //get table element var table = document.getElementById("myTable"); var headerLine = ""; //create html5 file reader object var myReader = new FileReader(); // call filereader. onload function myReader.onload = function(e) < var content = myReader.result; //split csv file using "\n" for new line ( each row) var lines = content.split("\r"); //loop all rows for (var count = 0; count < lines.length; count++) < //create a tr element var row = document.createElement("tr"); //split each row content var rowContent = lines[count].split(","); //loop throw all columns of a row for (var i = 0; i < rowContent.length; i++) < //create td element var cellElement = document.createElement("td"); if (count == 0) < cellElement = document.createElement("th"); >else < cellElement = document.createElement("td"); >//add a row element as a node for table var cellContent = document.createTextNode(rowContent[i]); cellElement.appendChild(cellContent); //append row child row.appendChild(cellElement); > //append table contents myTable.appendChild(row); > > //call file reader onload myReader.readAsText(theFile.files[0]); > else < alert("This browser does not support HTML5."); >> else < alert("Please upload a valid CSV file."); >return false; >

I have explained the Javascript code above line by line in comments.

Читайте также:  Css градиент в бэкграунде

When the Button is clicked, the ProceeFile JavaScript function is called.

Inside the function, first a check is performed to verify whether the file is a valid CSV or a text file. Then a check is performed to make sure whether the browser supports HTML5 File API.

Once above details are checked, CSV file is parsed , line by line and it’s contents are showed in HTML table.

For example, let’s consider this is our sample CSV file contents

Here is the sample Gif image of the output

You can also take a look at the JSFilddle

Reading CSV using External API in jQuery or Javascript

You can also use external API like Papa parse to read CSV file, it is an open source, well-maintained project and also free.

Using this API, you can create HTML code as below

 
and after including papaparse.js library in your project, we will be calling a submit callback function to perform parse operation. Our first task is to initialize papa parse.
$('#submit').on("click",function(e)< e.preventDefault(); $('#files').parse(< config: < delimiter: "auto", complete: GenerateTable, >, before: function(file, inputElem) < //console.log("Parsing file. ", file); >, error: function(err, file) < //console.log("ERROR:", err, file); >, complete: function() < //console.log("Done with all files"); >>); >);

Now, we need to define external function «GenerateTable» to create table and show data

function GenerateTable(results)< var markup = " markup+= ""; > markup+= "
"; $("#myTable").html(markup); >

That’s it, we are done, hope you are read CSV using Javascript, but I will strongly recommend using 1st method which is pure Javascript based.

Источник

How to read CSV with JavaScript — Browser and Node solutions

Posted on Jul 01, 2022

CSV files are text files that contain comma-separated values. The CSV format is flexible and language-independent, so it can be processed using any programming language.

This tutorial will help you learn how to read CSV data with JavaScript code.

There are two ways to read CSV based on where you read the file from:

You will learn how to read CSV files using both third-party and native modules.

Let’s see how to read CSV files and parse them into data from the Node.js environment first.

Read CSV data in Node.js environment (using csv-parse)

To read a CSV file from Node.js environment, you can use the csv-parse module from npm.

The csv-parse is a reliable CSV parser module that has been used for several years by Node developers. It’s a part of the node-csv module, which is a set of libraries used to manipulate CSV files using Node.js.

You will also need the native fs module to help you get a file from the file system.

First, install csv-parse on your project with npm:

Next, import both fs and csv-parse modules into your JavaScript file:

To read a CSV file using csv-parse , you need to create a readable stream using the fs.createReadStream() function.

The following example code shows how to create a readable stream with fs . Replace the ./example.csv parameter with the path to your CSV file:

Next, pipe the stream data as an input to the parse() function as shown below:

The row is an array filled with your CSV data. Suppose you have an example.csv file with the following content:

When you run the JS file using node, here’s the result:

 , , , , Alternatively, you can generate an object for each CSV row where the data is formatted as key-value pair. The first row (header) will be used as the keys.

To do so, you only need to change the options passed to the parse() method as shown below:


The ltrim option is used to trim the whitespace from your data.

Next, create an empty array variable named data , and push each row into the array.

Once all data has been processed, log the result:

  The result will be as follows:
   , Country: , Country: And that’s how you read a CSV file using JavaScript in Node.js environment.

Let’s see how you can read CSV files without csv-parse next.

Read CSV file with Node.js native module

To read a CSV file without using a module like csv-parse , you need to use the native Node modules fs and readline .

To read the whole file input at once, use the fs.readFile() method as shown below:

The output will be a string that you can further process whether as an array or object.

You can also read the file a row at a time by using fs.createReadStream() and readline modules.

In the following code example, a readable stream is sent into the readline.createInterface() method:

The readline interface will read each line and trigger the line event.

When the reading is done, readline will execute the close event function.

Although you can read a CSV file without using a third-party module, you will need extra work to format the output of the read process.

In the example above, the header row is processed just like the data rows. You need to write more code to format the CSV text better.

What’s more, the native code won’t work when you have edge cases, such as no line break between values (only one row in the file)

A module like csv-parse has been tested and refined through the years to handle parsing CSV well.

Unless you really have to write your own solution, it’s better to use csv-parse .

Read CSV file from the browser with D3.js

To read a CSV file from the browser, you need to use a different library named D3.js.

D3.js is a data manipulation library used to process data using JavaScript. One of its features is to read CSV files.

To use D3.js, you can download the latest release or import the script from a CDN.

Call the csvParse() method and pass a string as shown below:

[email protected]"The output will be an array of objects like this:
But if you’re parsing CSV file from the browser, then you usually need to receive a CSV file using the HTML element.

You can use the FileReader API and D3.js to read a CSV file using the following code:

[email protected]"First, you need to receive a file using the HTML :
Then, write an event listener for when the form is submitted using JavaScript.

Here, the uploaded csv file will be processed using D3.js:

     This is a standard implementation of D3.js to read CSV files from the browser.

For more information, you can look into the csvParse documentation.

Now you’ve learned how to parse CSV file using JavaScript and D3.js from the browser.

For a native solution in the browser, you can see my JavaScript CSV to array guide.

Thanks for reading. I hope this tutorial has been useful for you. 🙏

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

JаvaScript: Как прочитать файл CSV и отобразить его содержимое с помощью JavaScript

В jаvascript класс FileReader доступен для чтения данных из файла. С его помощью вы можете читать и просматривать содержимое файла перед его загрузкой на сервер.

В этом уроке я покажу, как можно использовать класс FileReader для чтения CSV-файла и отображения его содержимого на странице с помощью jаvascript.

1. Структура файла CSV

В примере я использую следующую структуру файла:

S.no,Username,Name,Email 1,yssyogesh,Yogesh singh,yogesh@makecodes.ru 2,bsonarika,Sonarika Bhadoria,bsonarika@makecodes.ru 3,vishal,Vishal Sahu,vishal@makecodes.ru 4,anilsingh,Anil singh,anilsingh@makecodes.ru

2. HTML

Создайте элемент файла и кнопку. Используйте для вывода списка выбранных данных CSV-файла. Добавьте событие onclick на кнопку. Оно вызывает функцию readCSVFile().

Готовый код

  table th, table td 




S.no Username Name Email

3. jаvascript - Чтение CSV

Создайте функцию readCSVFile(), которая вызывается при нажатии на кнопку. Проверьте, выбран ли файл или нет.

Чтение файла CSV и отображение данных

  • Создайте объект класса FileReader, если выбран файл.
  • Передайте экземпляр файла в readAsText() для чтения его данных как строки.
  • Добавьте событие onload на объект reader. Оно вызывается, когда файл успешно прочитан.
  • Используйте свойство result для получения данных файла. Присвойте эти данные переменной csvdata.
  • Разделите строковые данные разрывом строки (\n), чтобы получить данные в формате массива.
  • Создайте экземпляр , в который нужно добавить данные.
  • Выполните цикл по массиву rowData. Здесь, чтобы не читать 1-ю строку, я присвоил переменной row =1, но вы можете присвоить 0, если хотите читать 1-ю строку.
  • Создайте пустой - tbodyEl.insertRow().
  • Разделите значение строки запятой (,), чтобы получить массив данных столбцов.
  • Выполните цикл по массиву rowColData для чтения данных столбцов. Создайте ячейку и добавьте значение столбца - rowColData[col].

Готовый код

function readCSVFile() < var files = document.querySelector('#file').files; if(files.length >0 ) < // Выбранный файл var file = files[0]; // Объект FileReader var reader = new FileReader(); // Читать файл как строку reader.readAsText(file); // Загрузить событие reader.onload = function(event) < // Чтение данных файла var csvdata = event.target.result; // Разделение по переносу строки для получения строк массива var rowData = csvdata.split('\n'); //  var tbodyEl = document.getElementById('tblcsvdata').getElementsByTagName('tbody')[0]; tbodyEl.innerHTML = ""; // Цикл по массиву строк (измените row=0, если вы также хотите прочитать 1-ю строку) for (var row = 1; row < rowData.length; row++) < // Вставить строку в конец таблицы var newRow = tbodyEl.insertRow(); // Разделить запятой (,), чтобы получить массив столбцов rowColData = rowData[row].split(','); // Цикл по столбцу строки массива for (var col = 0; col < rowColData.length; col++) < // Вставить ячейку в конце строки var newCell = newRow.insertCell(); newCell.innerHTML = rowColData[col]; >> >; >else < alert("Пожалуйста, выберите файл."); >>

Вы можете использовать этот код для отображения предварительного просмотра данных файла или модифицировать код для применения валидации.

Настройте код в соответствии с вашим CSV-файлом при реализации этого в вашем проекте.

функция чтенияCSVFile()<
var files = document.querySelector('#file').files;

// Выбранный файл
var файл = файлы [0];

// Объект FileReader
var reader = новый FileReader();

// Читаем файл как строку
читатель.readAsText (файл);

// Загрузить событие
reader.onload = функция (событие)

// Чтение данных файла
var csvdata = событие.цель.результат;

// Разделить по разрыву строки, чтобы получить массив строк
var rowData = csvdata.split('\n');

//
var tbodyEl = document.getElementById('tblcsvdata').getElementsByTagName('tbody')[0];
tbodyEl.innerHTML = "";

// Цикл по массиву строк (измените row=0, если вы также хотите прочитать 1-ю строку)
for (var row = 1; row < rowData.length; row++)

// Вставляем строку в конец таблицы
var newRow = tbodyEl.insertRow();

// Разделить запятой (,), чтобы получить массив столбцов
rowColData = rowData[строка].split(',');

// Цикл по столбцу строки Массив
for (var col = 0; col < rowColData.length; col++)

// Вставляем ячейку в конец строки
var newCell = newRow.insertCell();
newCell.innerHTML = rowColData[col];

Источник

How to read csv file in node js

Here I want to get the elements in the column ID and store those in an array. How can I do that? Can anyone suggest me help. Thanks. My controller:

var partnersModel = new partners(params); fs.readFile(config.csvUploadPath, function read(err, data) < if (err) < throw err; >dataArray = data.toString().split(/\r?\n/); dataArray.forEach(function(v,i) < if(v !== 'DUI')< partnersModel.dui.push(v); >>); >); partnersModel.save(function(error, response) 

Is this actually a CSV file, or just a file containing a list of IDs? This would be pretty easy to parse without a library, but if you are parsing true CSV definitely use one! My module of choice is: npmjs.com/package/csv

This is not really CSV then, it is just a file with data on each row. You could use data.split('\n') [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. It would return an array like you desire.

3 Answers 3

Use a library, CSV has lots of gotchas. I have come to enjoy the package csv . It is located here: https://www.npmjs.com/package/csv . Here is a very quick example using the async api.

const fs = require('fs') var parse = require('csv-parse') fs.readFile(inputPath, function (err, fileData) < parse(fileData, , function(err, rows) < // Your CSV data is in an array of arrys passed to this callback as rows. >) >) 

Since your file does not have multiple values per row and contains no delimiters besides newline, it is only trivially CSV. Maybe String.prototype.split() is for you?

const fs = require('fs') fs.readFile(inputPath, 'utf8', function (err, data) < var dataArray = data.split(/\r?\n/); //Be careful if you are in a \r\n world. // Your array contains ['ID', 'D11', . ] >) 

Источник

Оцените статью