ASP. NET Import and Export of Excel
Last Update:2018-12-05
Source: Internet
Author: User
String filename = EMP. employeeid + "_" + year + "_" + month + ". xls ";
String Path = server. mappath ("http://www.cnblogs.com/") + @ "upfile \" + filename;
String worktable = request ["table"]. tostring () + "$ ";
Sqlconnection myconn = new sqlconnection (connectionstring );
String SQL = "select * From OpenRowSet ('Microsoft. jet. oledb.4.0 ', 'excel 5.0; HDR = yes; IMEX = 1; database = "+ path +"', ["+ worktable +"]) ";
Sqlcommand cmd = new sqlcommand (SQL, myconn );
Myconn. open ();
Sqldataadapter ADP = new sqldataadapter (CMD );
ADP. Fill (DS );
Myconn. Close ();
Return Ds;
Read the Excel file and write it to the database.
String urlpath = httpcontext. Current. Request. applicationpath + "/upfile /";
String physicpath = httpcontext. Current. server. mappath (urlpath );
String filename = EMP. employeeid + ". xls ";
String Path = physicpath + filename;
String strconn = "provider = Microsoft. Jet. oledb.4.0; Data Source =" + physicpath + filename + "; extended properties = Excel 8.0 ;";
Oledbconnection conn = new oledbconnection (strconn );
Conn. open ();
System. Data. oledb. oledbcommand cmd = new oledbcommand ();
Cmd. Connection = conn;
Try
{
Cmd. commandtext = "create table monthbudget (No. Int, Id int, project code varchar, budget project varchar, budget amount varchar for the same period last year, amount completed last month varchar, budget amount this month varchar, payment object varchar, contract information varchar, details varchar )";
Cmd. executenonquery ();
For (INT I = 0; I <Ds. Tables [0]. Rows. Count; I ++)
{
Int J = I + 1;
Datarow DR = Ds. Tables [0]. Rows [I];
Cmd. commandtext = "insert into [monthbudget] (sequence number, ID, project code, budget project, budget amount for the same period last year, amount completed last month) values (" + J + "," + convert. toint32 (Dr ["budgetitemid"]) + ", '" + Dr ["itemcode"] + "', '" + Dr ["itemname"] + "', '"+
Dr ["lastbudgetamount"] + "','" + Dr ["expendedamount"] + "')";
Cmd. executenonquery ();
}
Conn. Close ();
Httpresponse response = httpcontext. Current. response;
Response. Clear ();
Response. writefile (physicpath + filename );
String httpheader = "attachment?filename=monthbudget.xls ";
Response. appendheader ("content-disposition", httpheader );
Response. Flush ();
System. Io. file. Delete (physicpath + filename); // delete a temporary document
Response. End ();
}
Read dataset and write Excel