數據集對於構建API模型和各種業務流程至關重要。這就是為什麼導入和導出CSV是經常需要的功能。
在本教程中,您將學習如何在Angular App中下載和導入CSV文件。我們將使用包含員工詳細信息的CSV文件。該代碼將用打字稿編寫。
>>在開始之前,您需要設置一個新的角度環境,創建一個具有初始應用程序的新工作區,然後開始服務。可以在官方教程中找到為您的Angular應用程序創建樣板的分步指南。
>這是樣本板應用程序的文件夾結構:
Root<br>-- src<br>---- app<br>------ app-routing.module.ts<br>------ app.component.css<br>------ app.component.html<br>------ app.component.ts<br>------ app.module.ts<br>---- models<br>---- services<br>------ csv.services.ts<br>---- index.html<br>---- main.ts<br>---- styles.css<br>
首先,讓我們創建一個簡單的類來建模員工。該模型將被角組件所消耗。
export class User {<br> name: string;<br> email: string;<br> city: string;<br>}<br>
服務訪問和呈現數據的原因。在我們的用例中,我們需要一項服務來下載和導入CSV數據。
>我們的服務文件是 的形式以文件的形式獲取文件的內容。輸入標籤具有諸如[Accept]>之類的屬性,並且 >,可以將上述功能與app.component.html appmont.html ,現在該構建 In this post, you saw how to upload and download CSV data, and how to parse CSV data into and out of a text file. private async getTextFromFile(event: any) {<br> const file: File = event.target.files[0];<br> let fileContent = await file.text();<br> <br> return fileContent;<br>}<br>
public async importDataFromCSV(event: any) {<br> let fileContent = await this.getTextFromFile(event);<br> this.importedData = this._csvService.importDataFromCSV(fileContent);<br>}<br>
<div>Export simple data</div><br><input<br> #fileUploadSimple<br> [accept]="'.csv'"<br> type="file"<br> class="file-input"<br> (change)="importDataFromCSV($event)"<br> hidden="true"<br>/><br><button (click)="fileUploadSimple.click()">Import from csv</button><br><br /><br /><br>
Live Demo
Conclusion
以上是如何使用Angular上傳和下載CSV文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!