Простите, если мой вопрос звучит глупо. Я просто не знаю, как найти решение. Я использую Angular-7 для внешнего интерфейса и Laravel-5.8 для внутреннего интерфейса моего веб-приложения. Я успешно экспортирую данные в Excel, используя Client-Side (Angular-7), и он экспортирует все.
Laravel
ApiController.php
public function indexShortcode()
{
$shortcodes = Shortcode::with('telco')->get();
return $shortcodes;
}
api.php
Route::get('indexShortcode', 'ApiController@indexShortcode');
Угловой
excel.service.ts
import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Injectable()
export class ExcelService {
constructor() { }
public exportAsExcelFile(json: any[], excelFileName: string): void {
console.log('toexcel server --- 2',json);
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
}
}
shortcode.compnent.ts
import { Component, OnInit } from '@angular/core';
import {ExcelService} from '../../../services/excel.service';
import { filter } from 'rxjs/operators';
import { ShortcodeService } from '../../../services/shortcode.service';
import { TokenService } from '../../../services/token.service';
import { Router } from '@angular/router';
import { Shortcode } from '../../../models/shortcode';
@Component({
selector: 'app-sms-shortcode-my',
templateUrl: './sms-shortcode-my.component.html',
styleUrls: ['./sms-shortcode-my.component.scss']
})
export class SmsShortcodeMyComponent implements OnInit {
shortcodes: Shortcode[];
isLoading: Boolean = false;
public searchText: string;
public filter: string;
shortcodePosts: Shortcode[] = [];
p: number = 1;
totalRecords = 0;
pageSize = 5;
constructor(
private shortcodeService: ShortcodeService,
private excelService:ExcelService,
private spinnerService: Ng4LoadingSpinnerService,) { }
ngOnInit() {
// Get shortcode detail
this.getShortcodes();
}
ngOnDestroy(): void {
document.body.className = '';
}
refresh(): void {
window.location.reload();
}
//sorting
key: string = 'name';
reverse: boolean = false;
sort(key){
this.key = key;
this.reverse = !this.reverse;
}
getShortcodes(): void {
this.spinnerService.show();
this.shortcodeService.getShortcodes()
.subscribe(
response => this.handleResponse(response),
error => this.handleError(error),
()=>this.spinnerService.hide()
);
}
exportAsXLSX():void {
this.shortcodeService.getShortcodes()
.subscribe((data: any) => {
this.shortcodePosts = data;
console.log('toexcel server --- 1 ', this.shortcodePosts);
});
console.log('local --- 1 -1 ', this.shortcodes);
if (this.shortcodePosts.length > 0)
{
console.log('count',this.shortcodePosts.length)
this.excelService.exportAsExcelFile(this.shortcodePosts, 'Shortcode');
}
}
protected handleResponse(response: Shortcode[]) {
this.isLoading = false,
this.shortcodes = response;
}
protected handleError(error: any) {
this.isLoading = false,
console.error(error);
}
}
шорткод.component.html
<table id="example2" class="table table-bordered table-hover table-striped table-condesed">
<button (click)="exportAsXLSX()" class="btn btn-block btn-primary" style="margin-right: 15px;" ><i class="fa fa-download"></i> Download Excel</button>
<thead>
<tr>
<th width="5%">#</th>
<th>Shortcode</th>
<th>Description</th>
<th>Telco</th>
<th width="15%">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let shortcode of shortcodes| filter:filter | paginate: { itemsPerPage: 5, currentPage: p }; let i = index">
<td>{{i + 1}}</td>
<td>{{shortcode?.name}}</td>
<td>{{shortcode?.description}}</td>
<td>{{shortcode?.telco?.name || 'Not available'}}</td>
<td>
<button class="btn btn-info" routerLink="/smscodeupdate/{{ shortcode?.id }}">Edit</button>
<button class="btn btn-warning" routerLink="/smscodedetail/{{ shortcode?.id }}" style="margin-left: 20px;"> View</button>
</td>
</tr>
</tbody>
</table>
В настоящее время я делаю экспорт на стороне клиента, чтобы преуспеть, используя Angular. Он экспортирует все из базы данных. Однако я хочу:
Экспортировать только отфильтрованные данные, которые видны на странице
Использовать экспорт Excel на стороне клиента с использованием Laravel-5.8и затем связать его с угловым интерфейсом
Как мне добиться этого?