References: http://www.cnblogs.com/jeffhsu/archive/2011/08/24/2152013.html
I have read the jeffhsu method, but I need to make an Excel template. I have improved it by referring to the online materials.
// Asp.net export EXCEL
Private void ExportExcel ()
{
// Temporary file
String tempFile = string. Format ("{0}/1_12.16.xls", System. Environment. GetEnvironmentVariable ("TEMP"), Guid. NewGuid ());
// Use OleDb to connect
OleDbConnection con = new OleDbConnection ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + tempFile + "; Extended Properties = Excel 8.0 ");
Using (con)
{
Con. Open ();
// Create a Sheet
OleDbCommand created CREATE = new OleDbCommand ("create table Sheet1 ([ID] VarChar, [name] VarChar, [time] VarChar)", con );
Using create. ExecuteNonQuery ();
// Insert data
OleDbCommand cmd = new OleDbCommand (@ "insert into [Sheet1 $] VALUES (@ ID, @ name, @ time)", con );
Cmd. Parameters. AddWithValue ("@ ID", "1 ");
Cmd. Parameters. AddWithValue ("@ name", "Haha ");
Cmd. Parameters. AddWithValue ("@ time", DateTime. Now );
Cmd. ExecuteNonQuery ();
}
Response. ContentType = "application/ms-excel ";
Response. AppendHeader ("Content-Disposition", "attachment?filename=info.xls ");
Response. BinaryWrite (File. ReadAllBytes (tempFile ));
File. Delete (tempFile );
}