2014-02-06 2 views
0

Excel로 내보내기 및 Excel 가져 오기가있는 gridview가 있습니다. 그러나 성공적으로 gridview에서 데이터를 내보낼 수 있고 같은 엑셀로 가져 오려고하면 그 Excel을 가져올 수 없습니다. 하지만 파일 이름을 변경하고 가져올 때 제대로 작동합니다.Excel을 표로 가져올 수 없습니다.

아무도 나에게 이런 일이 일어나는 이유를 제안 할 수 있습니까? 아래는 Import to Grid to excel에 대한 코드입니다.

protected void btnImport_Click(object sender, EventArgs e) 
{ 
    string sexcelconnectionstring = ""; 
    string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower(); 
    string path = FileUploadExcel.PostedFile.FileName; 
    string query = ""; 
    Label1.Text = ""; 
    GridView2.Visible = false; 

    if (strFileType != String.Empty) 
    { 
     //Connection String to Excel Workbook 
     if (strFileType.Trim() == ".xls") 
     { 
      sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"; 
     } 
     else if (strFileType.Trim() == ".xlsx") 
     { 
      sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; 
     } 

     OleDbConnection conn = new OleDbConnection(sexcelconnectionstring); 
     if (conn.State == ConnectionState.Closed) 
      conn.Open(); 

     System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 

     string sheetname = dt.Rows[0]["Table_Name"].ToString(); 

     try 
     { 
      query = "SELECT [Size],[Order],[Ratio] FROM [" + sheetname + "]"; 
      OleDbCommand cmd = new OleDbCommand(query, conn); 
      OleDbDataAdapter da = new OleDbDataAdapter(cmd); 
      DataSet ds = new DataSet(); 
      da.Fill(ds); 
      if (objDA.IsValidExcelColumns(ds, GridView2, strSqlTable)) 
      { 
       string sclearsql = "delete from " + strSqlTable; 
       SqlConnection sqlconn = new SqlConnection(strConnectionString); 
       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); 
       oledbconn.Open(); 
       OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn); 
       OleDbDataReader dReader; 
       dReader = oledbcmd.ExecuteReader(); 
       SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnectionString); 
       sqlBulk.DestinationTableName = strSqlTable; 
       sqlBulk.WriteToServer(dReader); 
       ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Data has been saved successfully.')", true); 
      } 

      else 
      { 
       ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please validate the excel data.')", true); 
      } 
     } 

     catch (Exception ex) 
     { 
      Label1.Text = "Upload status: The file could not be uploaded due to invalid column names.Please check: " + ex.Message; 
     } 

     conn.Close(); 
     conn.Dispose(); 
     objDA.BindGrid(GridView1, "select * from " + strSqlTable); 
    } 
    else 
    { 
     ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true); 
    } 
} 

다음은 Excel로 내보내는 코드입니다.

+0

하는 행에서 오류가 발생하고 오류가 무엇입니까? –

+0

이 줄에서 발생합니다 conn.Open(); sexcelconnectionstring 바로 아래에. 오류 : 사용자 코드가 OleDbException을 처리하지 못했습니다. 외부 테이블이 예상 된 형식이 아닙니다. –

+0

제안 사항 : 오래된 xls 파일을로드 할 필요가없는 경우 안전하게 epplus와 같은 라이브러리를 사용하여 파일을로드 할 수 있습니다. 그것은 더 빠르고 훨씬 더 신뢰성있는 것입니다. –

답변

-1

데이터를 내보내는 방법을 지정해주십시오. 데이터를 내보내기 위해 사무실 INTEROP 서비스를 사용하고 있습니까? 그렇다면 가비지 수집기를 사용하여 Excel 응용 프로그램 개체를 처리하십시오. 그런 다음 Excel에서 데이터를 가져 오십시오.

데이터를 엑셀 파일로 내보낼 때 작업 관리자에 새로운 excel.exe가 만들어 졌다고 생각됩니다. 데이터 내보내기 후에 Excel을 종료하지 않은 경우 개체, 그것은 여전히 ​​메모리에있을 것입니다. 따라서 동일한 Excel을 표로 가져 오려고하면 파일이 이미 사용 중이며 삭제되지 않으므로 예외가 발생합니다.

using Marshal = System.Runtime.InteropServices.Marshal; To close excel application - excel.quit(); To dispose excel object - Marshal.ReleaseComObject(excel);

+0

게시물의 코드를 Excel로 내보내기하도록 업데이트했습니다. –

관련 문제