#html #angular #typescript
#HTML #угловатый #typescript
Вопрос:
Я пытаюсь создать угловое приложение, которое берет данные из таблицы Excel и отображает их в таблице при загрузке. Я добавил edit
ссылку под одним столбцом для редактирования данных строки, при нажатии на «Редактировать» она отображается save
и cancel
нажимается. Я попытался реализовать эту функциональность с помощью некоторых компонентов, но все получилось не так, как я ожидал. Может ли кто-нибудь подсказать мне способ реализовать это, пожалуйста?
-> app.component.html
<div>
<h3>Upload Excel File</h3>
<div class="row">
<input type="file" (change)="uploadFile($event)" placeholder="Choose File" accept=".xls,.xlsx,.ods">
<button type="button" class="btn btn-info" (click)="upload()" >Upload</button>
</div>
</div>
<br>
<div>
<table *ngIf="submitted">
<tr>
<th *ngFor = "let column of tableHeaders">
{{column}}
</th>
</tr>
<tr *ngFor = "let row of excelData; let i=index">
<td >
{{row["Employee Name"]}}
</td>
<td>
{{row["Email Id"]}}
</td>
<td>
{{row["UID"]}}
</td>
<td>
{{row["place"]}}
</td>
<td>
{{row["DOB"]}}
</td>
<td>
<button *ngIf="enableEdit amp;amp; enableEditIndex == i" (click)="enableEdit=false" class="btn page-secondary-action-btn" ng-click="cancel()">Cancel</button>
<button *ngIf="enableEdit amp;amp; enableEditIndex == i" id="saveBtn" class="btn page-primary-action-btn" (click)="saveSegment()" type="submit">Save</button>
<a href="#" class="table-row-action edit-action" *ngIf="!enableEdit" (click)="editRowData($event, i)">Edit</a>
</td>
</tr>
<tr>
</tr>
</table>
</div>
-> app.component.ts
import { Component } from '@angular/core';
import * as XLSX from 'xlsx';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'excelUpload';
buffer: any;
file: File;
worksheet: any;
excelData: any[];
excelDatas: any[];
tableData: any[];
uploadFile(event) {
this.file = event.target.files[0];
}
private dataLoaded: boolean;
submitted: boolean = false;
tableHeaders = ["Employee Name", "Email Id", "place", "UID", "DOB", "Actions"];
tableRows = [];
enableEdit: boolean = false;
enableEditIndex = null;
upload() {
this.submitted = true;
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.buffer = fileReader.result;
var data = new Uint8Array(this.buffer);
var arr = new Array();
for (var i = 0; i != data.length; i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name]; // worksheet_name
this.excelData = XLSX.utils.sheet_to_json(worksheet, { raw: true })
this.excelDatas = this.excelData.map(data => Object.values(data));
console.log(this.excelData);
// console.log(this.excelData[0]["Email Id"]);
// var newArr = this.excelData.map((data, index) => {
// console.log(data)
// })
}
fileReader.readAsArrayBuffer(this.file);
}
editRowData(e, i) {
this.enableEdit = true;
this.enableEditIndex = i;
}
saveSegment(){}
}
Ответ №1:
Я смог исправить свою проблему с NG-ZORRO
компонентами. Компоненты таблицы NG-ZORRO имеют Editable Cells
компонент, с помощью которого я смог редактировать каждую строку внутри таблиц.
Ссылка: Нажмите здесь для справки
=> app.component.ts
import { Component } from '@angular/core';
import * as XLSX from 'xlsx';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'edit-table';
i = 0;
editId: string | null = null;
listOfData: any;
file: File;
buffer: any;
worksheet: any;
excelData: any[];
tableData: any;
uploadFile(event) {
this.file = event.target.files[0];
}
submitted: boolean = false;
// function to read data from excel
upload() {
this.submitted = true;
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.buffer = fileReader.result;
var data = new Uint8Array(this.buffer);
var arr = new Array();
for (var i = 0; i != data.length; i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name]; // worksheet_name
this.excelData = XLSX.utils.sheet_to_json(worksheet, { raw: true })
// this.tableData = this.excelData.map(data => Object.values(data));
}
fileReader.readAsArrayBuffer(this.file);
}
startEdit(id: string): void {
this.editId = id;
}
stopEdit(): void {
this.editId = null;
}
addRow(): void {
this.tableData = [
];
this.i ;
}
deleteRow(id: string): void {
this.tableData = this.tableData.filter(d => d.id !== id);
}
}
=> app.component.html
<div>
<h3>Upload Excel File</h3>
<div class="row">
<input type="file" (change)="uploadFile($event)" placeholder="Choose File" accept=".xls,.xlsx,.ods">
<button type="button" class="btn btn-info" (click)="upload()" >Upload</button>
</div>
</div>
<br />
<br />
<nz-table #editRowTable nzBordered [nzData]="excelData" *ngIf="submitted">
<thead>
<tr>
<th>Employee Name</th>
<th>Email Id</th>
<th>UID</th>
<th>place</th>
<th>DOB</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of editRowTable.data" class="editable-row">
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['Employee Name'] }}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['Employee Name']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['Email Id']}}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['Email Id']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['UID']}}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['UID']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['Place'] }}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['Place']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['DOB'] }}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['DOB']" (blur)="stopEdit()" />
</td>
</tr>
</tbody>
</nz-table>