C# Excel 데이터를 데이터베이스로 가져오기 위한 구현 코드
c#将Excel数据导入到数据库的实现代码
假如Excel中的数据如下:
数据库建表如下:
其中Id为自增字段:
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.OleDb; using System.Configuration; using System.Data.SqlClient; namespace InExcelOutExcel { public partial class ExcelToDB : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { FileSvr fileSvr = new FileSvr(); System.Data.DataTable dt = fileSvr.GetExcelDatatable ("C:\\Users\\NewSpring\\Desktop\\Demo\\InExcelOutExcel\\InExcelOutExcel\\excel\\ExcelToDB.xlsx", "mapTable"); fileSvr.InsetData(dt); } } class FileSvr { /// <summary> /// Excel数据导入Datable /// </summary> /// <param name="fileUrl"></param> /// <param name="table"></param> /// <returns></returns> public System.Data.DataTable GetExcelDatatable(string fileUrl, string table) { //office2007之前 仅支持.xls //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';"; //支持.xls和.xlsx,即包括office2010等版本的 HDR=Yes代表第一行是标题,不是数据; const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; System.Data.DataTable dt = null; //建立连接 OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl)); try { //打开连接 if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed) { conn.Open(); } System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); //获取Excel的第一个Sheet名称 string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim(); //查询sheet中的数据 string strSql = "select * from [" + sheetName + "]"; OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn); DataSet ds = new DataSet(); da.Fill(ds, table); dt = ds.Tables[0]; return dt; } catch (Exception exc) { throw exc; } finally { conn.Close(); conn.Dispose(); } } /// <summary> /// 从System.Data.DataTable导入数据到数据库 /// </summary> /// <param name="dt"></param> /// <returns></returns> public int InsetData(System.Data.DataTable dt) { int i = 0; string lng = ""; string lat = ""; string offsetLNG = ""; string offsetLAT = ""; foreach (DataRow dr in dt.Rows) { lng = dr["LNG"].ToString().Trim(); lat = dr["LAT"].ToString().Trim(); offsetLNG = dr["OFFSET_LNG"].ToString().Trim(); offsetLAT = dr["OFFSET_LAT"].ToString().Trim(); //sw = string.IsNullOrEmpty(sw) ? "null" : sw; //kr = string.IsNullOrEmpty(kr) ? "null" : kr; string strSql = string.Format("Insert into DBToExcel (LNG,LAT,OFFSET_LNG,OFFSET_LAT) Values ('{0}','{1}',{2},{3})", lng, lat, offsetLNG, offsetLAT); string strConnection = ConfigurationManager.ConnectionStrings["ConnectionStr"].ToString(); SqlConnection sqlConnection = new SqlConnection(strConnection); try { // SqlConnection sqlConnection = new SqlConnection(strConnection); sqlConnection.Open(); SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = strSql; sqlCmd.Connection = sqlConnection; SqlDataReader sqlDataReader = sqlCmd.ExecuteReader(); i++; sqlDataReader.Close(); } catch (Exception ex) { throw ex; } finally { sqlConnection.Close(); } //if (opdb.ExcSQL(strSql)) // i++; } return i; } } }
运行结果:
以上就是c#将Excel数据导入到数据库的实现代码的内容,更多相关内容请关注PHP中文网(www.php.cn)!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











C#을 사용한 Active Directory 가이드. 여기에서는 소개와 구문 및 예제와 함께 C#에서 Active Directory가 작동하는 방식에 대해 설명합니다.

C#의 난수 생성기 가이드입니다. 여기서는 난수 생성기의 작동 방식, 의사 난수 및 보안 숫자의 개념에 대해 설명합니다.

C# 데이터 그리드 뷰 가이드. 여기서는 SQL 데이터베이스 또는 Excel 파일에서 데이터 그리드 보기를 로드하고 내보내는 방법에 대한 예를 설명합니다.

멀티 스레딩과 비동기식의 차이점은 멀티 스레딩이 동시에 여러 스레드를 실행하는 반면, 현재 스레드를 차단하지 않고 비동기식으로 작업을 수행한다는 것입니다. 멀티 스레딩은 컴퓨팅 집약적 인 작업에 사용되며 비동기식은 사용자 상호 작용에 사용됩니다. 멀티 스레딩의 장점은 컴퓨팅 성능을 향상시키는 것이지만 비동기의 장점은 UI 스레드를 차단하지 않는 것입니다. 멀티 스레딩 또는 비동기식을 선택하는 것은 작업의 특성에 따라 다릅니다. 계산 집약적 작업은 멀티 스레딩을 사용하고 외부 리소스와 상호 작용하고 UI 응답 성을 비동기식으로 유지 해야하는 작업을 사용합니다.
