AngularJS implements php-generated excel file download function example based on http requests,
The example in this article describes how AngularJS downloads the excel file generated by php Based on http requests. We will share this with you for your reference. The details are as follows:
Everyone who uses the PHPExcel plug-in knows that exporting excel directly changes the generated content to the content-type to download the content as a file. At this time, a url on the page needs to be downloaded by clicking.
So the question is, if there is a request parameter when generating an excel file, you can only use the http request of js. How can you download it at this time?
The following methods are available:
1. angularjs creates a tag for simulated download
// Create a tag to simulate downloading function exportExcel (params, filename) {return $ http ({url: '/api/exportExcel', method: "POST", headers: {'content-type': 'application/json'}, params: params, responseType: 'arraybuffer '}). success (function (data) {var blob = new Blob ([data], {type: "application/vnd. openxmlformats-officedocument.spreadsheetml.sheet "}); var objectUrl = URL. createObjectURL (blob); var a = document. createElement ('A'); document. body. appendChild (a);. setAttribute ('style', 'display: none');. setAttribute ('href ', objectUrl);. setAttribute ('Download', filename);. click (); URL. revokeObjectURL (objectUrl );});}
Note that if the xls file is transmitted, that is, the excel5 file, set type to application/vnd. ms-excel or application/x-excel.
2. js generates a url for the request parameter and creates a tag
// Generate the download url $ scope. data. down_url = "../c_potential/get_excel? End_time = "+ $ scope. end_date + "& liable =" + liable + "& nickname =" + $ scope. data. nickname + "& province =" + $ scope. data. province_cur + "& start_time =" + $ scope. start_date;
Then, bind the url to a certain a tag. This method is suitable for scenarios with few parameters and data is not processed twice, making it difficult to produce errors. The only drawback is that it needs to be processed twice, you can set two buttons. One is generated, the parameter is written to the url, and the other is downloaded to excel. Although the user performs two operations, only one http request actually occurs without affecting the performance.
3. Download the package
The third method is similar to the second method. First, an excel file is generated, stored on the server, and downloaded. Disk I/O is involved, so the performance is relatively low. This method is not recommended, but is recorded as a method.
Angularjs is the most convenient method for simulating download, but error may occur. The second method is the safest.