2012-09-14 65 views
1

我想找到使用fileupload控件選擇excel電子表格(xls和xlsx),然後使用filestream對象解析並填充數據集的最佳方法。從文件上傳控制讀取spreadsheetl文件到文件流

這是我的代碼到目前爲止,它的工作,但它的不同之處在於我將Excel電子表格保存到我的解決方案中的文件夾,然後使用Microsoft ACE OLEDB連接查詢數據。

protected void btnUpload_Click(object sender, EventArgs e) 
    { 
     string connectingString = ""; 
     if (ctrlFileUpload.HasFile) 
     { 
      string fileName = 
       Path.GetFileName(ctrlFileUpload.PostedFile.FileName); 

      string fileExtension = 
       Path.GetExtension(ctrlFileUpload.PostedFile.FileName); 
       //Path.GetExtension(ctrlFileUpload.PostedFile.ContentType); 

      string fileLocation = 
       Server.MapPath("~/App_Data/" + fileName); 
      ctrlFileUpload.SaveAs(fileLocation); 

      // Check whether file extension is xls or xslx 
      if (fileExtension == ".xls") 
      { 
       connectingString = 
        "Provider=Microsoft.ACE.OLEDB.4.0;Data Source=" + 
        fileLocation + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\""; 
      } 

      else if (fileExtension == ".xlsx") 
      { 
       connectingString = 
        "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + 
        fileLocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\""; 
      } 

      // Create OleDb Connection and OleD Command 
      using (OleDbConnection con = new OleDbConnection(connectingString)) 
      { 
       try 
       { 
        OleDbCommand cmd = new OleDbCommand(); 
        cmd.CommandType = CommandType.Text; 
        cmd.Connection = con; 
        OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd); 
        //DataTable dtExcelRecords = new DataTable(); 
        DataSet ds = new DataSet(); 
        con.Open(); 
        DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 

        string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString(); 
        cmd.CommandText = "Select * FROM [" + getExcelSheetName + "]"; 
        dAdapter.SelectCommand = cmd; 
        //dAdapter.Fill(dtExcelRecords); 
        dAdapter.Fill(ds); 
        //GridView1.DataSource = dtExcelRecords; 
        //GridView1.DataBind(); 
       } 
       catch (Exception ex) 
       { 

       } 
      } 

     } 
    } 

所以,總結我想讀在電子表格中的數據,然後將其綁定到數據集,但沒有將文件保存到一個物理路徑。

有沒有一種更清晰的方式來編寫我缺少的代碼。謝謝!!

+0

錢德拉是你的同事之一嗎? http://stackoverflow.com/q/12420310/284240 –

+0

大聲笑他不是,但我會看看那個鏈接。謝謝! –

+0

沒有任何解決方案可以使用,無需下載自定義類庫? –

回答

0

我認爲它不可能得到不保存文件到您的服務器

如果您不能保存uploded文件,你怎麼給Data Source您的OleDbConnection字符串數據?

如果您不想保留該文件,則可以在完成此執行後刪除文件。

你也可以用這種方式參照https://stackoverflow.com/a/12420416/284240

+0

這是我向我的經理提出的建議,但他認爲使用filestream讀取文件會更好。 –