asp.net build Excel file and download (update: Solve the problem of using Thunder to download pages instead of files) _ Practical Tips

Source: Internet
Author: User
Tags file url httpcontext int size save file
Here is a method of using the file address to download the Excel file in the server.

To generate an Excel file, see: "Original". NET to create Excel files (insert data, modify formatting, generate charts)

First try the Response.WriteFile method:
Copy Code code as follows:

FileInfo fi = new FileInfo (excelfile);//excelfile to the address of the file on the server
HttpResponse contextresponse = HttpContext.Current.Response;
Contextresponse.clear ();
Contextresponse.buffer = true;
Contextresponse.charset = "GB2312"; Set the type to prevent the appearance of garbled characters
Contextresponse.appendheader ("Content-disposition", String.Format ("attachment;filename={0}", ExcelName)); Defining output files and file names
Contextresponse.appendheader ("Content-length", fi. Length.tostring ());
contextresponse.contentencoding = Encoding.default;
Contextresponse.contenttype = "Application/ms-excel";//Set Output file type to excel file.

Contextresponse.writefile (FI. FullName);
Contextresponse.flush ();
Contextresponse.end ();

The first line of Excelfile is the address of the Excel file on the server, such as "C:\Website\Excel\xx.xlsx".

This method is also commonly provided on the Internet, but in the actual operation, but there is no intention to the problem:

Under the Chrome

All normal, Excel files are downloaded directly to the Chrome default download folder.

Under the Firefox

Because the FlashGot plugin is installed, you will first select the Application Download tool:

Shown here is normal, if you choose "Save File", the Excel file will also be saved to the default folder, but if you try a third-party download tool, such as thunder, the following window will appear:

Note that the URL column will add viewstate information after the actual address of the page, and the save name is not the name of the Excel file itself, but the name of the page.

After clicking OK, the downloaded file becomes the actual file (sometimes it becomes a. zip file, and then it becomes a real file).

Under the IE7

Will pop up the Save dialog box, the file is normal, also because of the thunder for the sake of, save, Pop-up Thunder Download dialog box, and Firefox under different, url behind no viewstate information.

Click OK, the download is the paging file:

If the download dialog box in the Thunder to cancel, you will use IE download, the file here is correct:

Suspected Thunder is based on the Download dialog box in the URL of the request to download, and launched the requested page has nothing to do, and IE will not send viewstate information to the Thunderbolt, resulting in the download file is not the desired Excel page.

And then tried to download the way, in fact, is also ineffective, because the Thunderbolt does not bother you to provide it with the download mechanism, and so in the Firefox down with the Thunderbolt, because the ViewState does not contain the complete information of Excel file, the Thunder download is also incomplete documents.

Finally, only the most old-fashioned solution: Response.Redirect (), to the actual file address.

Copy Code code as follows:

FileInfo fi = new FileInfo (excelfile);
HttpResponse contextresponse = HttpContext.Current.Response;
Contextresponse.redirect (String. Format ("~/template/{0}", Excelname), false);

In this way, the test in three browsers is normal, because the request is the actual file address, in the Thunderbolt display is also the actual file address. There is no problem with downloading. However, this is equivalent to informing the client user of the actual address of the file, the privacy of the poor. But the good news here is that it doesn't require too much privacy, and the file will be deleted after a certain time, so it's not too much of a problem.

It was the first consideration and it seemed to be a little lazy ...

After consideration, since each thunderbolt is actually a request URL, then we should give the Thunder to pass a can generate Excel file URL.

That is, when you click the "Generate Excel" button, turn to another export page, and in the Page_Load method of this page, complete the steps to build Excel files and download Excel files.
Copy Code code as follows:

String fileName = request.querystring["filename"];
String exportname = request.querystring["Export"];
if (fileName!= null)
{
Exportmanger.createexcel (fileName);//First create Excel file on server side.
Response.Redirect (String.Format ("{0}")? Export={1} ", Request.Path.ToString (), fileName);//Redirect to this page, but the query parameter becomes export.
}
else if (exportname!= null)
{
Exportmanger.exportexcel (exportname);//download Excel file.
}

Here the page jumps two times, the first time is to build Excel, the second is to download Excel.

The reason to jump two times, is because the Thunderbolt will capture the final URL, if the build and download put together, then the Thunder download will be reproduced repeatedly into an Excel file. The Code exportmanger.exportexcel (exportname) for downloading an Excel file uses the Response.Write method that is described at the beginning of this article, or it can be downloaded in a segmented way:
Copy Code code as follows:

if (FI. Length > 0)
{
FileStream sr = new FileStream (FI. Fullname,system.io.filemode.open,system.io.fileaccess.read, System.IO.FileShare.Read);
int size = 1024;//Sets the length of each read.
for (int i = 0; I < fi. Length/size + 1; i++)
{
byte[] buffer = new Byte[size];
int length = Sr. Read (buffer, 0, size);
ContextResponse.OutputStream.Write (buffer, 0, length);
}
Sr. Close ();
}
Else
{
Contextresponse.writefile (FI. FullName);
}

The result here is that only one Excel is generated and kept on the server, and the same files are downloaded using the "Export" parameter each time you download it. So if you need files that are one-time and need to be regenerated for each download, you just need to put the download and build of the export page together. And then turn the Response.Write method of the beginning into the final:
Copy Code code as follows:

Contextresponse.flush ();
Fi. Delete ();
Contextresponse.end ();

That is, every time the response is emptied, the file is deleted first, then the response is terminated. This solves the problem of not downloading with the download tool, protects the privacy of the server file address, writes the large file in a segmented write, and deletes the generated file as needed, without consuming server space.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.