2016-12-21 2 views
-3

사용자가 Excel 파일에서 C# WinForms 응용 프로그램을 사용하여 한 번에 하나씩 파일로 데이터를 전송하도록합니다. Excel 파일은 비슷한 열로 구성되어 있으므로 새로운 열이나 열이 없을 수 있습니다. 행 데이터는 다양합니다.다른 열이있는 SQL 테이블로 Excel 데이터 전송

엑셀 파일 1 : 이름, 도시 국가
엑셀 파일 2 : 예를 들어

, 이름, 도시

카운티 : 이름,시,
Excel에서 3 파일 우편 번호 이름, 도시, 인구, 학교

나는 새 Excel을 삽입하려면 어떻게 : 기존 SQL 테이블에서

나는 열이 비슷한 열 이름을 가진 파일을 기존 SQL 데이터베이스에 저장 하시겠습니까?

내 생각은 지금까지 임시 테이블에 새 Excel 파일의 데이터를 복사 한 다음 기존 SQL 테이블에 그를 삽입하는 것입니다. 문제는 C# 코드 (또는 SQL 쿼리)를 작성하여 기존 SQL 테이블보다 더 많거나 적은 열로 새 Excel 데이터를 삽입하는 방법을 모르겠다는 것입니다.

답변

1

이 목적을 위해 No-SQL이 필요합니다. 테이블에 아직 포함되어 있지 않은 열을 입력해야한다면 SQL은 좋은 옵션이 아닙니다. C#에서 alter table까지 사용하면 결과에주의해야합니다. 당신 앞에있는 모든 열 이름에 대해 확신하는 경우

0

이 너무 힘들 should't 삽입 시작하기 전에 다음 테이블을 변경하려고합니다. Excel에서 SQL Server의 준비 테이블 테이블로 데이터를 내 보냅니다. C# 코드는 다음과 비슷할 수 있습니다.

public void importdatafromexcel(string excelfilepath) 
{ 
    //declare variables - edit these based on your particular situation 
    string ssqltable = "tdatamigrationtable"; 
    // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have 
    different 
    string myexceldataquery = "select student,rollno,course from [sheet1$]"; 
    try 
    { 
     //create our connection strings 
     string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath + 
     ";extended properties=" + "\"excel 8.0;hdr=yes;\""; 
     string ssqlconnectionstring = "server=mydatabaseservername;user 
     id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false"; 
     //execute a query to erase any previous data from our destination table 
     string sclearsql = "delete from " + ssqltable; 
     sqlconnection sqlconn = new sqlconnection(ssqlconnectionstring); 
     sqlcommand sqlcmd = new sqlcommand(sclearsql, sqlconn); 
     sqlconn.open(); 
     sqlcmd.executenonquery(); 
     sqlconn.close(); 
     //series of commands to bulk copy data from the excel file into our sql table 
     oledbconnection oledbconn = new oledbconnection(sexcelconnectionstring); 
     oledbcommand oledbcmd = new oledbcommand(myexceldataquery, oledbconn); 
     oledbconn.open(); 
     oledbdatareader dr = oledbcmd.executereader(); 
     sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring); 
     bulkcopy.destinationtablename = ssqltable; 
     while (dr.read()) 
     { 
      bulkcopy.writetoserver(dr); 
     } 

     oledbconn.close(); 
    } 
    catch (exception ex) 
    { 
     //handle exception 
    } 
} 

그런 다음 SQL Server에서 준비 테이블의 데이터를 최종 프로덕션 테이블로 이동합니다. SQL은 다음과 같이 보일 수 있습니다.

insert into production 
select ... 
from staging 
where not exists 
(
    select 1 from staging 
    where staging.key = production.key 
) 

그건 내 .02입니다. 나는 당신이 그런 식으로 모든 과정을 훨씬 더 잘 제어 할 것이라고 생각합니다.

0

당신이이 질문을 읽고 있다면 당신이 다음이 다른 질문에 대한 내 대답은 도움이 될 수있다 (다만이 파일을 엑셀 각 행 정보, 프로세스를 처리하고 같은 대량 삽입을 수행하는 클래스를 만들고 거기에 설명) :

Bulk insert is not working properly in Azure SQL Server

는 나는 그것이 도움이되기를 바랍니다.

관련 문제