Asp tutorial. net xls file download function example
Provides two asp.net tutorial c files to download the instance code. If you directly connect to the xls file, it will be opened in the browser. Now we use. net to download the instance.
*/
Private void page_load (object sender, system. eventargs e)
{
If (! Page. ispostback)
{
String filepath = "d: www.bKjia.c0m.xls ";
// Filepath = "d: test.xls ";
System. io. filestream fs = system. io. file. openread (filepath );
Byte [] filedata = new byte [fs. length];
Fs. read (filedata, 0, (int) (fs. length ));
Fs. close ();
Response. addheader ("content-type", "application/vnd. ms-excel ");
String saveasfilename = "yoursaveasfilename ";
Saveasfilename = encode (saveasfilename );
// Saveasfilename = httputility. urldecode (saveasfilename, system. text. encoding. getencoding ("shift-jis "));
Response. addheader ("content-disposition", "inline; filename =" + saveasfilename );
Response. addheader ("content-length", filedata. length. tostring ());
Response. binarywrite (filedata );
Response. end ();
}
}
// Method 2
Public static void downloadfile (string filepath)
{
String str = httpcontext. current. request. servervariables ["appl_physical_path"];
String path = str + "www. bKjia. c0m" + filepath;
Fileinfo file = new fileinfo (path );
Httpcontext. current. response. contentencoding = system. text. encoding. getencoding ("UTF-8"); // solves Chinese garbled characters
Httpcontext. current. response. addheader ("content-disposition", "attachment; filename =" + httpcontext. current. server. urlencode (file. name); // solves Chinese file name garbled characters
Httpcontext. current. response. addheader ("content-length", file. length. tostring ());
Httpcontext. current. response. contenttype = "appliction/octet-stream ";
Httpcontext. current. response. writefile (file. fullname );
Httpcontext. current. response. end ();
}