Link to home
Start Free TrialLog in
Avatar of GoldenJag
GoldenJag

asked on

Write data from excel file to a table in SQL Database

Andy,

The next step is to take the info from the Excel file and write it to a table in SQL DB.
Avatar of GoldenJag
GoldenJag

ASKER

This is officially what my code looks like:

private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
{
      int fileid = Convert.ToInt32(DataGrid1.SelectedItem.Cells[1].Text);
      com.solu.webservices.Crypt ws = new com.solu.webservices.Crypt();
      byte[] test = ws.DecryptStoredFile(pm.sessionKey,fileid);
                  
      //WRITE TO TEMP FILE
      //string FileName = Path.GetTempFileName();
      string FileName = @"C:\temp.xls";
      FileStream File_Stream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
      try
      {
            File_Stream.Write(test,0,test.Length);
      }
      catch(Exception ex)
      {
            Response.Write(ex.Message.ToString());
      }
      finally
      {
            File_Stream.Close();
      }

                                                  //NEXT STEP:
                  //WRITE to info from Excel file to SQL  Table via ODBC

OK, cool.

Is this the new code? You should be careful with the FileStream object ... the using {} block we had is a better way of doing it as it ensures that the stream is both flushed and disposed once you've finished.

Other than that, you now want to write from Excel to SQL, unfortunately I haven't had much success with this in the past. ODBC and Excel is a bit of a nightmare - the data-type detection is very dodgy.

However, I can point you to this place to get you started: http://www.codeproject.com/csharp/Excel_using_OLEDB.asp

Hopefully that will help, or someone else will join in this question to add some more advice. Feel free to ask for more details as you go.

Andy
I found the solution: it is

string strConn;

                  strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                        "Data Source= C:\\temp.xls;" +
                        "Extended Properties=Excel 8.0;";
                  //You must use the $ after the object you reference in the spreadsheet
                  OleDbConnection objConn = new OleDbConnection(strConn);
            objConn.Open();
                  OleDbCommand myCommand = new OleDbCommand("SELECT * FROM [Sheet1$]",objConn);
                  
                  OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

                  objAdapter1.SelectCommand = myCommand;

                  DataSet myDataSet = new DataSet();

                  objAdapter1.Fill(myDataSet, "XLData");
                  DataGrid1.DataSource = myDataSet.Tables[0].DefaultView;
                  DataGrid1.DataBind();
Fine by me
ASKER CERTIFIED SOLUTION
Avatar of GranMod
GranMod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial