2015-01-20 2 views
0

asp.net mvc4 응용 프로그램을 만들고 있는데, 엑셀 시트의 데이터베이스 테이블에 데이터를 쓸 수 있습니다 (sqlbulkcopy 열 매핑 사용). 엑셀 시트를 선택하여 제출하면 데이터베이스에 데이터를 쓰고 있습니다.여러 데이터베이스 행에 대해 상수 (동일한) 타임 스탬프를 설정합니다.

이제 데이터베이스 테이블에 데이터를 쓸 때 각 데이터 행에 대한 시간 소인으로 파일 업로드 시간을 설정하려고합니다.

코드 :

namespace AFFEMS2_HEC.Controllers 
{ 
    public class ExcelController : Controller 
    { 
     // 
     // GET: /Excel/ 

     public ActionResult Index() 
     { 
      return View(); 
     } 


     [HttpPost] 
     [AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Index(HttpPostedFileBase FileUpload1) 
     { 
      //Upload and save the file 
      if (Request.Files["FileUpload1"].ContentLength > 0) 
      { 
       string excelPath = Path.Combine(HttpContext.Server.MapPath("~/Content/"), Path.GetFileName(FileUpload1.FileName)); 

       FileUpload1.SaveAs(excelPath); 

       string conString = string.Empty; 
       string extension = Path.GetExtension(FileUpload1.FileName); 
       switch (extension) 
       { 
        case ".xls": //Excel 97-03 
         conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString; 
         break; 
        case ".xlsx": //Excel 07 or higher 
         conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString; 
         break; 

       } 
       conString = string.Format(conString, excelPath); 
       using (OleDbConnection excel_con = new OleDbConnection(conString)) 
       { 

        string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString(); 
        string sheet2 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1]["TABLE_NAME"].ToString(); 

        DataTable dtExcelData = new DataTable(); 


        //[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default. 

        dtExcelData.Columns.AddRange(new DataColumn[4] { 
        new DataColumn("Id", typeof(string)), 
        new DataColumn("Name", typeof(string)), 
        new DataColumn("Email",typeof(string)), 
        new DataColumn("Mobile", typeof(int)) }); 


        string query = "SELECT s1.Id, " + 
             "s1.Name, " + 
             "s1.Mobile, " + 
             "s2.Email " + 
             "FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)"; 

        using (OleDbDataAdapter oda = new OleDbDataAdapter(query, excel_con)) 
        { 
         oda.Fill(dtExcelData); 
        } 
        excel_con.Close(); 

        string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 
        using (SqlConnection con = new SqlConnection(consString)) 
        { 
         using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con, 
                SqlBulkCopyOptions.CheckConstraints| 
                SqlBulkCopyOptions.FireTriggers| 
                SqlBulkCopyOptions.KeepNulls| 
                SqlBulkCopyOptions.TableLock| 
                SqlBulkCopyOptions.UseInternalTransaction, 
                null)) 
         { 
          //Set the database table name 
          sqlBulkCopy.DestinationTableName = "User1"; 

          sqlBulkCopy.ColumnMappings.Add("Id", "Id"); 
          sqlBulkCopy.ColumnMappings.Add("Name", "Name"); 
          sqlBulkCopy.ColumnMappings.Add("Email", "Email"); 
          sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile"); 

          con.Open(); 

          try 
          { 
           // Write from the source to the destination 
           sqlBulkCopy.WriteToServer(dtExcelData); 
          } 
          catch (Exception ex) 
          { 
           Console.WriteLine(ex.Message); 
          } 
          finally 
          { 
           con.Close(); 
          } 
         } 
        } 
       } 

      } 
      return View(); 
     } 
    } 
} 
+0

내가 한 행과 내일 나는 것 또 다른 행을 삽입하지만 두 행에 대해 동일한 타임 스탬프를 필요로 오늘합니다. –

+0

아니요 내가 작성한 행에 대한 타임 스탬프로 설정된 시트 업로드 시간 (각 기록 된 시간이 아닌)을 능가하려고합니다. – Chathz

+0

그게 당신을 위해 일한거야 ?? –

답변

0

그냥 "TimeStamp_Inserted"로 다른 열을 만들 수 있지만 날짜 또는 NVARCHAR 해야 입력하고 코드

   string query = "SELECT s1.Id, " + 
            "s1.Name, " + 
            "s1.Mobile, " + 
            "s2.Email " + 
            "'"+DateTime.Now.ToString() +"'"+" as TimeStamp_Inserted"+ 
            "FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)"; 

SqlBulkCopy의 다음과 같은 대체하려고 열 매핑이 이렇게 변경하려고합니다

은 그것을 시도

+0

괜찮아요, 안내해 주셔서 감사합니다. – Chathz

관련 문제