Vue + AXIOS + WebAPI + NPOI Exports Excel File Example Method

First, preface

The ELEMENT UI framework used in the project, the remote data request, the AXIOS, the backend interface frame, the ASP.NET WebAPI, Data export into Excel uses NPOI components. Its business scenario, mainly the list page (such as membership information, order information, etc.) table data export, such as the table data, and requires the condition to be transmitted to the backend API, after filtering the data, export into Excel.

Three plans to think about the front end:

1. Use location.href to open the interface address. Disadvantages: You cannot pass the Token to the backend API, unable to ensure the security check of the interface, And the interface can only be a GET method request.

2. Using the AXIOS request interface, first generate a file and save it after the filter data server, then return to the remote file address, and use location.href to open the file address. Download. Disadvantages: Implementation, and each export will generate files at the server, but there is no suitable timing to trigger the delete file again, which will form garbage data on the server. Advantages: You can have records each time.

3. Using the AXIOS request interface, the server API returns the file stream. After receiving the file flow, the BLOB object is stored, and it is created into a URL, use a tag download. Advantages: front-end can be transmitted token parameter school Introduce interface security and support both GET or POST.

Because its application scenarios are exported Excel files, data must be filtered, and the interface security is required to check, so the third solution is the best choice. After Baidu, it is found that the most use of the current use is the third solution.

Second, Vue + AXIOS front-end processing

AXIOS needs to be processed in the response interceptor (here no longer introducing the use of Axios, For the usage of AXIOS, please check the AXIOS Chinese description, we have done AXIOS in the project.Unified interception definitions). Need special attention: Response.Headers [‘content-disposition “, the default is not available, you need to configure the server WebAPI, please see the webapi Cors configuration in the third point

// Respone interceptor service.interceptors.response.Use (response => {// blob type is file download object, no matter what request, return to file stream data IF (Response .config.responsetype === ‘blob’) {const filename = decodeuri (response.Headers [‘content-disposition’]. Split (‘filename =’) [1]) // Return to file stream content, and get file name The acquisition of Response.Headers [‘Content-Disposition’] is not obtained by default. You need to configure Return Promise.Resolve ({data:, filename: filename})} // based on the server WebAPI. The actual situation of the end logic, you need a pop-up display friendly error}, error => {let resp = error.response if ( {Console.log (‘Err:’ + decodeuricomponent ( // for debug } // TODO: Requires Return Promise.reject (Error)}} (
 2. Click the Export button to request the APINeed to note that the response type of the interface request configured ResponseType: 'blob' (or configuring arraybuffer); the IE9 and the following browser do not support CreateObjectURL. Requires the IE to convert BLOB into files under the IE browser.   
Exportexcel () {let params =} let p = this.getQueryParams () // Get the corresponding parameter IF (p) params = Object ({}, params , p) AXIOS .GET (‘interface address’, {params: params, responsetype:’ blob ‘}) .Then (res => {var blob = new blob ([res. Data], {type:’ Application / VND .ms-excel; charset = uTF-8 ‘}) // For the IE browser processing, CreateObjectURL if (Window.navigator && Window.navigator.Mssaveoropenblob) {Window.Navigator.MssaveorOpenBlob is not supported by the IE browser blob, res.fileName)} else {var downloadElement = document.createElement ( ‘a’) var href = window.URL.createObjectURL (blob) // create the download link downloadElement.href = href = res.fileName after // download file name document.body.appendChild (downloadElement) () // Download document.body.removeChild (downloadElement) // download is complete remove elements window.URL.revokeObjectURL (href) // release Blob object}}}}

Third, WebAPI + NPOI backend processing

 1. need to pass the interface Parameters, Query Data   In order to maintain the parameters that have been queried with the paging component, the GET request mode is used to facilitate front end convetrients. WebAPI interface must return ihttpactionResult type 

public httpactionResult exportData ([fromuri] PAGINATION PAGINATION, [FROMURI] ORDERREQDTO DTO) {// Remove Data Source DataTable Dt = THIS .Service.getMemberpageList ()); if (dt.rows.count> 65535) {throw new exception (“The maximum number of outlets is 65535 lines, please filter data!”);} Foreac DataRow Row In Dt.Rows) {var isrealName = row [“isRealName”]. TobOOL (); row [“isrealName”] = isRealName? “Yes”: “No”;} var model = new exportmodel (); = jsonconvert.serializeObject (dt); model.FileName = “Member Information”; Model.title = model; model.lstcol = new list (); model.lstcol.add (new exportDataColumn () {Prop = “fullname”, label = “Member Name”}); Model.lstcol. Add (new exportdatacolumn () {prop = “realname”, label = “real name”}; model.lstcol.add (new exportDataColumn () {Prop = “gradeName”, label = “member”}); model. LSTCOL.ADD (New ExportDataColumn () {Prop = “Telphone”, label = “phone”}); model.lstcol.add (new exportDataColumn () {Prop = “aaname”, label = “区域”}); model. LSTCOL.ADD (New ExportDataColumn () {Prop = “GridName”, label = “Grid”}; model.lstcol.add (new exportDataColumn () {Prop = “address”, label= “House number”}); model.lstcol.add (new exportDataColumn () {Prop = “regtime”, label = “registration time”}); model.lstcol.add (new exportDataColumn () {Prop = “description” , label = “Note”}); return exportDataByfore (Model);}
2. Implementation of key derived function ExportDataByfore

[HttpGet] public IHttpActionResult ExportDataByFore (ExportModel dto) {var dt = JsonConvert.DeserializeObject
(dto.Data); var fileName = dto.FileName + DateTime.Now.ToString ( “yyMMddHHmmssfff”) + “. xls “; // set export format ExcelConfig excelconfig = new ExcelConfig (); excelconfig.Title = dto.Title; excelconfig.TitleFont =” Microsoft elegant black “; excelconfig.TitlePoint = 25; excelconfig.FileName = fileName; excelconfig.IsAllSizeColumn = True; / / Each column is set, no column information set, the system will be exported according to the column name in DataTableXcelConfig.columnentity = new list (); // Metet Foreach (VAR COL IN DTO.LSTCOL) {Excelconfig.Columnentity.Add (New ColumnEntity () {Column = Col.Prop, ExcelColumn = col.label}) } // Call the export method var stream = ExcelHelper.ExportMemoryStream (DT, Excelconfig); // Draw data into an Excel file through NPOI and forms a memory stream VAR Browser = String.empty; if (httpContext.current.Request.USERAGENT ! = null) {browser = HttpContext.Current.Request.UserAgent.ToUpper ();} HttpResponseMessage httpResponseMessage = new HttpResponseMessage (HttpStatusCode.OK); httpResponseMessage.Content = new StreamContent (stream); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue (“Application / OcTet-Stream”); ​​// Return Type must be the file stream Application / OcTet-stream httpresponseMessage.Content.Headers.contentDisposition = new ContentDispositionHeaderValue ( “attachment”) // set the head other content properties, the file name {FileName = browser.Contains ( “FIREFOX”) fileName: HttpUtility.UrlEncode (fileName)?}; return ResponseMessage (httpResponseMessage);}
   3. WEB API CORS configuration  
Using the WEB API to build a classmate, you know that the interface needs to solve cross-domain issues. CORS configuration for API, which is mainly for the front-end AXIOS response to the Content-Disposition property in Response Header, performs the following configuration

Fourth, summary
   The above is some of the issues I have encountered when I implement AXIOS export Excel file function, and the key points. Because the project involves some of the core source of the front-rear end of other business and the company's architecture. To extract a complete Demo, it is time consuming, so there is no complete Demo display. But I have put NPOI-related operation function source, and put it on GitHub. Https://                     
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment