您好,登錄后才能下訂單哦!
本篇內容主要講解“C#怎么讀取Excel中數據并插入到數據庫中”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C#怎么讀取Excel中數據并插入到數據庫中”吧!
C#讀取Excel中數據,首先上傳選擇的xls文件,根據得到路徑,讀取文件信息,插入到數據庫中。
using System.Data; using System.Data.OleDb; using System.IO; using System.Text; protected void Page_Load(object sender, EventArgs e) { } public void ExcelToDS(string path) { string strSheetName = "sheet1"; string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +path + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; //Sql語句 string strExcel = "select * from [" + strSheetName + "$] "; DataSet ds = new DataSet(); //連接數據源 OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); //適配到數據源 OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, conn); adapter.Fill(ds, "data"); conn.Close(); GridView1.DataSource = ds.Tables["data"]; GridView1.DataBind(); Label1.Text = ds.Tables[0].Rows.Count.ToString(); SqlAccess.Sqldatabase sql = new SqlAccess.Sqldatabase(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { sb.Append("insert into data values('" + ds.Tables[0].Rows[i]["companyname"] + "','" + ds.Tables[0].Rows[i]["telname"] + "','" + ds.Tables[0].Rows[i]["qytel"] + "','" + ds.Tables[0].Rows[i]["fax"] + "');"); } sql.ExecuteNonQuery(CommandType.Text, sb.ToString()); } protected void Button1_Click(object sender, EventArgs e) { string fileName = null; try { Boolean fileOK = false; String path = Server.MapPath("./doc/"); if (FileUpload2.HasFile) { String fileExtension = System.IO.Path.GetExtension(FileUpload2.FileName).ToLower(); String[] allowedExtensions = { ".xls" }; //C#讀取Excel中數據 for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } if (fileOK) { fileName = "r_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + DateTime.Now.Millisecond + System.IO.Path.GetExtension(FileUpload2.FileName).ToLower(); if (File.Exists(path + fileName)) { Random rnd = new Random(10000); fileName = fileName + rnd.Next(); } FileUpload2.PostedFile.SaveAs(path + fileName); } else { } } catch (Exception exp) { } ExcelToDS(Server.MapPath(".") + "\\doc\\"+fileName); }
C#讀取Excel中數據并插入到數據庫中就介紹到這里。
到此,相信大家對“C#怎么讀取Excel中數據并插入到數據庫中”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。