Using the way HTML is stitched into table table, return fileresult output a binary file.
The first type: using Filecontentresult
////Summary://Create a Filecontentresult object by using the file content, content type, file name////Parameters://FileContents://The contents of the binary file in response//// ContentType: Span style= "color: #008000;" >// content Type (MIME type) ////< Span style= "color: #008000;" > Filedownloadname: // display the file name in the browser download window //// return result: // file Content object. protected internal Virtual Filecontentresult File (byte[] filecontents, string filedownloadname);
Need to convert the contents of a file into a byte array byte[]
byte[] filecontents = Encoding.Default.GetBytes (sbhtml.tostring ());
The second type: using Filestreamresult
Other parameter description same as Filecontentresult // parameter: // fileStream: ////// String filedownloadname);
Need to convert the contents of a file into a stream
New MemoryStream (filecontents);
The third type: using Filepathresult
Other parameter description same as Filecontentresult // parameter: // fileName: ////// Virtual Filepathresult File (string filedownloadname);
The Excel file must first be available on the server and will be returned by the Server.MapPath get path.
Please see the code for details.
Exportexcel Code
1PublicFileresult Exportexcel ()2{3var sbhtml =NewStringBuilder ();4 Sbhtml.append ("<table border= ' 1 ' cellspacing= ' 0 ' cellpadding= ' 0 ' >");5 Sbhtml.append ("<tr>");6var lsttitle =New list<string> {"Number","Name","Age","Creation time"};7foreach (VAR itemInchLsttitle)8{9 Sbhtml.appendformat ("<TD style= ' Font-size:14px;text-align:center; Font-weight:bold, ' height= ' >{0}</td>", item);10}Sbhtml.append ("</tr>");1213for (int i =0; I <1000; i++)14{Sbhtml.append ("<tr>");Sbhtml.appendformat ("<TD style= ' font-size:12px;height:20px; ' >{0}</td>"+ N);Sbhtml.appendformat ("<TD style= ' font-size:12px;height:20px; ' > Cock Wire {0} # </td>"+ N);Sbhtml.appendformat ("<TD style= ' font-size:12px;height:20px; ' >{0}</td>",New Random (). Next (20,30) +i);Sbhtml.appendformat ("<TD style= ' font-size:12px;height:20px; ' >{0}</td>", DateTime.Now);Sbhtml.append ("</tr>");21st}Sbhtml.append ("</table>");2324//The first type: using Filecontentresult25byte[] FileContents =Encoding.Default.GetBytes (Sbhtml.tostring ());26Return File (FileContents,"Application/ms-excel","Filecontents.xls");2728//The second type: using Filestreamresult29var fileStream =NewMemoryStream (filecontents);30Return File (FileStream,"Application/ms-excel","Filestream.xls");3132// The third type: Use Filepathresult 33 //34 var fileName = Server.MapPath ( "~/files/filename.xls" ); 35 return File (FileName, "application/ms-excel " filename.xls "); 36}
ASP. NET MVC uses Fileresult to export Excel data files