The problems encountered in development are this:
In the process of maintaining the old management system, the boss said let the export function; In the project, the filter criteria for the query are written in the form submitted.
There are two types of solutions:
First, using the Ajax way to export
var array = $ (' #frmSearch '). Serialize ();
After obtaining the form data, post to the server, the server returns the network address of the file, and then use Windows.open () to download the file
But I hope that after the file is downloaded, the file can be deleted, using the top way is not appropriate, can not delete the old files in time, so think of the following way:
Second, the way to download the file stream
Because Ajax can not handle the file stream, so can not be used to submit data in Ajax, can only use form form forms to submit data, but the question, how can a form form to implement two functions?
The solution is, we can simulate a form in JS, the code is as follows:
var $frm = $ (' <form action= "" method= "Post" ></form> "); var array = $ (' #frmSearch '). Serializearray (); for (i = 0, length = array.length; i < length; i++) { = array[i].name; = Array[i].value; $frm. Append (' <input name = ' + key + ' "value =" ' + value + ' "/> ')); } $frm. Submit ();
The server-side processing flow is this: ① query data According to the filter criteria, and then generate Excel;② to convert the file to a file stream, ③ delete the file, ④ set the response header, output file stream data;
The simple example code is as follows:
//① query data based on filter criteria, and then generate ExcelList<tradeviewmodel> modellist = ...;stringFileName;stringPath = Exporthelper.exportdatatoexcel (Modellist,"trademodel.xlsx","Revenue record Export list", New[] {"A","B","C","D","E","F","G","H","I","J","K" }, New[] {"Id","Subject","payer","Receiver","Manager","Recorder","Amount","Payway","PayDate","Receipt","Status" }, outfileName);//② converting files to file streamsbyte[] bytes;using(FileStream fs =NewFileStream (Path, FileMode.OpenOrCreate, FileAccess.Read)) {bytes=New byte[(int) fs. Length]; Fs. Read (Bytes,0, Bytes. Length);}//③ Delete the fileSystem.IO.File.Delete (path);//④ Setting the response header, output file stream dataResponse.ContentType ="Application/octet-stream";//notifies the browser to download a file instead of opening itResponse.AddHeader ("content-disposition","attachment; Filename="+Httputility.urlencode (FileName, System.Text.Encoding.UTF8)); Response.BinaryWrite (bytes); Response.Flush (); Response.End ();
Data table, query, export share a form form, to achieve file stream mode download