Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, How to save csv file data in database in angular 10?
Story Behind this post:
Guys, I was working on angular project and I had task to read and save scv file data in angular 10 but I faced some difficulties and I almost spent full day on it but I have done it and I am sharing this post to help others.
Angular 12 came and if you are new then you must check below two links:
Friends now I proceed onwards and here is the working code snippet for How to save csv file data in database in angular 10? and please use this carefully to avoid the mistakes:
1. Firstly friends we need fresh angular 10 setup and for this we need to run below commands but if you already have angular 10 setup then you can avoid below commands. Secondly we should also have latest node version installed on our system:
npm install -g @angular/cli ng new angularcsv //Create new Angular Project cd angularcsv // Go inside the Angular Project Folder ng serve --open // Run and Open the Angular Project http://localhost:4200/ // Working Angular Project Url
2. Now friends, here we need to run below commands into our project terminal to install bootstrap modules(for good looks) into our angular application:
npm install --save bootstrap ng serve --o
3. Now friends, here we need to add below into our angular.json file:
"styles": [ ... "node_modules/bootstrap/dist/css/bootstrap.min.css" ]
4. Now friends, we need to add below code into our src/app/app.component.ts file:
... import { HttpClient } from '@angular/common/http'; export class AppComponent { ... constructor(private http: HttpClient) {} //array varibales to store csv data lines = []; //for headings linesR = []; // for rows //File upload function changeListener(files: FileList){ console.log(files); if(files && files.length > 0) { let file : File = files.item(0); console.log(file.name); console.log(file.size); console.log(file.type); let reader: FileReader = new FileReader(); reader.readAsText(file); reader.onload = (e) => { let csv: any = reader.result; let allTextLines = []; allTextLines = csv.split(/\r|\n|\r/); // console.log(allTextLines); //Table Headings let headers = allTextLines[0].split(';'); let data = headers; let tarr = []; for (let j = 0; j < headers.length; j++) { tarr.push(data[j]); } //Pusd headinf to array variable this.lines.push(tarr); // Table Rows let tarrR = []; //Create formdata object var myFormData = new FormData(); let arrl = allTextLines.length; let rows = []; for(let i = 1; i < arrl; i++){ rows.push(allTextLines[i].split(';')); if(allTextLines[i]!=""){ // Save file data into formdata varibale myFormData.append("data"+i, allTextLines[i]); } } for (let j = 0; j < arrl; j++) { tarrR.push(rows[j]); tarrR = tarrR.filter(function(i){ return i != ""; }); // Begin assigning parameters } //Push rows to array variable this.linesR.push(tarrR); //Sending post request with data to php file return this.http.post('http://localhost/mypage.php/' , myFormData).subscribe((res: Response) => { console.log("User Registration has been done."); }); } } } }
5. Now friends we just need to add below code into src/app/app.component.html file to show csv data into bootstrap data table:
<div class="container"> <h1 class="mt-4">TheRichPost.com</h1> <input class="form-control mb-5" type="file" class="upload" (change)="changeListener($event.target.files)"> <table class="table table-bordered table-dark mt-5"> <thead> <tr> <th *ngFor="let item of lines[0]; let i = index">{{item}}</th> </tr> </thead> <tbody> <tr *ngFor="let item of linesR[0]; let i = index"> <td *ngFor="let itemm of lines[0]; let j = index">{{item[j]}}</td> </tr> </tbody> </table> </div>
6. Now friends, we need to add below code into our src/app/app.module.ts file:
... import {HttpClientModule, HttpClient} from '@angular/common/http'; ... imports: [ ... HttpClientModule, ]
7. Finally friends, here is php file code and my php file is xampp/htdocs/mypage.php and we need to add below code into it:
//My databse name is users and my table name is formdata with id, username, identifier, firstname, lastname fields.
<?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: PUT, GET, POST"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); $conn = new mysqli('localhost','root','','users'); if(isset($_POST)) { //row count $datacount = count($_POST); $data = array(); //String to array conversion of all the rows for($a = 1; $a<=$datacount; $a++) { $data[$a] = explode(";",$_POST["data".$a]); } for($b = 1; $b<=$datacount; $b++) { //insert query $sql = "INSERT INTO formdata (username, identifier, firstname, lastname) VALUES ('".$data[$b][0]."', ".$data[$b][1].", '".$data[$b][2]."', '".$data[$b][3]."')"; if ($conn->query($sql) === TRUE) { $myJSON = json_encode("New user created successfully"); } else { $myArr = "Error: " . $sql . "<br>" . $conn->error; $myJSON = json_encode($myArr); } echo $myJSON; } } ?>
Now we are done friends. If you have any kind of query, suggestion and new requirement then feel free to comment below.
Note: Friends, In this post, I just tell the basic setup and things, you can change the code according to your requirements. For better live working experience, please check the video on the top.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad because with your views, I will make my next posts more good and helpful.
Jassa
Thanks
Hi,
Can u tell me please How to save csv data into mongodb with angular?
Thanks in advance
Okay, I will show you post on this.
Thank you so much 🙂
Hi,
Can u tell me please How to save csv data into SQL Server with angular10 ?
Yes you can use same angular code to save data in sql server.
Puedes actualizar el codigo para angular 12 ?
yes sure.