Create an array by extracting data from the chosen CSV file using the file input type

I am looking to utilize AngularJS to read and store the data from a CSV file that is uploaded using an input type file.

My approach involves leveraging AngularJS with an input type file to handle CSV, xls, or xlsx files in the following manner:

HTML:

<input class="btn btn-default col-xs-6" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onchange="angular.element(this).scope().checkFormat(this.files)">

JavaScript/AngularJS:

$scope.checkFormat = function(files) {
        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);
}

What is the best way for me to iterate through this CSV file row by row and add each row into an array?

Answer №1

If you want to streamline the process, creating a custom directive is the way to go. Let's name it csvUpload and utilize it like this:

<csv-upload ng-model="myData">
. This approach promotes reusability and saves you from duplicating the logic in multiple controllers. It's not only efficient but also convenient - with just a few clicks, your data will be readily available on $scope.myData :)

Here's how I tackled it:

(For converting CSV to JSON, I rely on the reputable https://github.com/mholt/PapaParse library. Although manual parsing is an option, I wouldn't recommend going down that path ;)

.directive('csvUpload', function () {
  return {
    restrict: 'E',
    template: '<input type="file" onchange="angular.element(this).scope().handleFiles(this.files)">',
    require: 'ngModel',
    scope: {},
    link: function (scope, element, attrs, ngModel) {
      scope.handleFiles = function (files) {
        Papa.parse(files[0], {
          dynamicTyping: true,
          complete: function(results) {
            // Additional data transformations can be performed here if needed
            // ...
            ngModel.$setViewValue(results);
          }
        });
      };

    }
  };
});

Answer №2

** The beauty of HTML

**

<input type="file" name="datasource_upload" accept="application/vnd.ms-excel, application/pdf,.csv" ngf-max-size="2MB" (change)="csv2Array($event)">

**

Journey into Typescript code

**

    csv2Array(fileInput: any){
//fetching file from input
this.fileReaded = fileInput.target.files[0];

let reader: FileReader = new FileReader();
reader.readAsText(this.fileReaded);

reader.onload = (e) => {
  let csv: string = reader.result;
  let allTextLines = csv.split(/\r|\n|\r/);
  let headers = allTextLines[0].split(',');
  let lines = [];

  for (let i = 0; i < allTextLines.length; i++) {
    // splitting content based on comma
    let data = allTextLines[i].split(',');
    if (data.length === headers.length) {
      let tarr = [];
      for (let j = 0; j < headers.length; j++) {
        tarr.push(data[j]);
      }

      // display each row to review output 
      console.log(tarr);
      lines.push(tarr);
    }
  }
  // check out all rows in the csv file 
  console.log(">>>>>>>>>>>>>>>>>", lines);
} }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty with rendering speed when reusing a directive in AngularJS

Here is a basic directive called "base": angular.module("base", []) .directive("base", function() { return { restrict: "A", scope: true, controller: function($scope) { this.setHeader = function(header) { $scope.h ...

Moving the layout container towards the left: a quick guide

I am currently attempting to display the legend contents in a horizontal alignment within the layout container. The issue is that while the layout containing the legend aligns horizontally as desired, it extends beyond the screen border. I do not want the ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Switching between sockets on a rotational basis

Imagine there is a division in the HTML file, and an interesting game is being played where each player has the opportunity to change the color. However, there’s a twist – they can only switch colors after the other player has taken their turn. The pla ...

Ways to address Path Traversal vulnerability in the following code

const downloadFile = blobstoreRouter.get('/blobstore/download/:filename', (req, res) => { var localFile = path.join(__dirname, '..', escape(req.params.filename)); var file = require('fs').createWriteStream(localFile); try { ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

Troubleshooting issue with password validation not functioning correctly within the Joi schema in React

I am working on developing a password change form using React. Below is the code snippet of my component: import React, { Component } from "react"; import Joi from "joi-browser"; import "./Login/Login.css"; import { UAA } from ...

Loading Animation for Pages and Tables

I'm experiencing a choppy and sudden transition when switching between two pages that contain tables populated using ng-repeat. Upon loading, the footer is positioned halfway up the page below the table heading until the table loads and the layout adj ...

Dynamic button group with scroll functionality in JavaScript/jQuery

Looking for assistance in creating a button group that includes a left and right arrow to scroll through the buttons when there are more than X amount in the group. The end result should resemble something like this: https://i.sstatic.net/FQXLE.jpg Tried ...

Back up and populate your Node.js data

Below is the Course Schema I am working with: const studentSchema = new mongoose.Schema({ name: { type: String, required: true }, current_education: { type: String, required: true }, course_name: { ...

Primary tag badge using Bootstrap design

I am currently following a React tutorial by Mosh, where he is using the badge badge-primary class in a span tag. import React, { Component } from "react"; class Counter extends Component { state = { count: 0, }; render() { return ...

The W3C validator verifies the cached iteration of the website

Click here The most recent error is on Line 420, Column 42: Found a stray start tag script. <script src="/skin/sayan_health/js/nc.js"></script> However, I managed to fix this error by placing the script tag inside the body tag. When I inspec ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Executing the callback function

I am facing a situation where I have a Modelmenu nested within the parent component. It is responsible for opening a modal window upon click. Additionally, there is a child component in the same parent component that also needs to trigger the opening of a ...

Focus on targeting each individual DIV specifically

Is there a way to toggle a specific div when its title is clicked? I have tried the following code snippet: $( '.industrial-product' ).find('.show-features').click(function() { $('.industrial-product').find('.ip-feat ...

What is the best JavaScript framework for implementing client-side hyphenation?

Looking to improve my website's readability, I want to implement client-side hyphenation using JavaScript for longer texts. Although CSS3 hyphenation is preferred, it's not always available. So far, I've been using Hyphenator.js, which, whi ...

Angular momentum issue detected

Developing an android app with a search function that includes input type date. Attempted to parse the input date from 2017-5-10T17:00:00.000Z to 2017-5-10 using moment.angular. Although the search function works, it results in an error that prevents the a ...

What is the method for determining the total, product, and remainder when working with a pair of global variables and a pair

I am new to JavaScript and struggling to understand the logic in my code. I have attempted to write some logic below, but I can't quite figure out what code to use to get the desired result. Could someone please assist me in correcting my code and exp ...

Creating a unique function to map an array in VueJS specifically designed for table manipulation

I am currently working on displaying and sorting data in a bootstrap table within VueJS. My goal is to change the date format within an array retrieved from an API endpoint. The original date format is in "January 21, 2010" and I need it to be in "MM/DD/Y ...

It is not possible to submit a hidden input when its value is changed

Has anyone encountered the same issue as mentioned in this question? I've searched for a solution, but unfortunately, I haven't been able to find one! I tried going through this answer, but it didn't work for me either! Would greatly appr ...