web| Access | data | download | Download In the application we may encounter such a situation, we need to temporarily generate a data file for users to download, but each download must be judged, that is, users do not get this download URL constantly download files, the following is the implementation method. The file is saved in CSV format to facilitate data import and export, the basic principle is to use the stream to write the file and then use Response.WriteFile to send the stream to the client.
Table structure with this article: http://blog.csdn.net/lovecherry/archive/2005/02/25/301441.aspx
SqlConnection conn=new SqlConnection (system.configuration.configurationsettings.appsettings["Conn"));
SqlDataAdapter Da=new SqlDataAdapter ("select * from TB1", conn);
DataSet ds=new DataSet ();
Da. Fill (ds, "Table1");
DataTable Dt=ds. tables["Table1"];
String name=system.configuration.configurationsettings.appsettings["DownloadURL"]. ToString () +datetime.today.tostring ("YyyyMMdd") +new Random (DateTime.Now.Millisecond). Next (10000). ToString () + ". csv";//stored in Web.config downloadurl specified path, file format is current date + 4-bit random number
FileStream fs=new FileStream (name,filemode.create,fileaccess.write);
StreamWriter Sw=new StreamWriter (fs,system.text.encoding.getencoding ("gb2312"));
Sw. WriteLine ("Automatic numbering, name, age");
foreach (DataRow dr in Dt. Rows)
{
Sw. WriteLine (dr["ID"]+ "," +dr["VName"]+ "," +dr["]);
}
Sw. Close ();
Response.AddHeader ("Content-disposition", "attachment; Filename= "+ server.urlencode (name));
Response.ContentType = "Application/ms-excel";//specifies that a stream that cannot be read by the client is returned and must be downloaded
Response.WriteFile (name); Send the file stream to the client
Response.End ();
In front of this code you can put some judgments, to determine whether this user can download files, generated files can be stored in the database, the next time you can download directly and do not repeat the file.