ASP.NET對EXCEL的匯入匯出

來源:互聯網
上載者: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;
讀Excel,然後寫到資料庫裡
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(序號 int,ID int,項目代碼 varchar, 預算項目 varchar,去年同期預算金額 varchar,上月完成金額 varchar,本月預算金額 varchar,付款對象 varchar,合約情況 varchar,具體內容 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] (序號,ID,項目代碼,預算項目,去年同期預算金額,上月完成金額) 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);//刪除臨時文檔
 response.End();   
}
讀DataSet寫EXCEL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.