-1

On a button click I am trying to export a excel file to a SQL Server table. First I created my first button which would create the table upon a click:

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
    string query = "CREATE TABLE [dbo].[" + textBox1.Text + "](" + "[Code] [varchar] (7) NOT NULL," +
       "[Description] [varchar] (38) NOT NULL," + "[NDC] [varchar] (12) NULL, " +
       "[Supplier Code] [varchar] (38) NOT NULL," + "[UOM] [varchar] (8) NULL," + "[Size] [varchar] (8) NULL,)";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(query, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

My next function is what should be the one which would grab the excel file through OpenFileDialog, select it and then upload the relevant contents to the table created from my button click above.This is the important section of the function:

private void button2_Click(object sender, EventArgs e)
{
    OpenFileDialog ope = new OpenFileDialog();
    ope.Filter = "Excel Files |*.xlsx;*.xlsm";

    if (ope.ShowDialog() == DialogResult.Cancel)
        return;

    FileStream stream = new FileStream(ope.FileName, FileMode.Open);
    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
    DataSet result = excelReader.AsDataSet();

    DataClasses1DataContext conn = new DataClasses1DataContext();

    foreach (DataTable table in result.Tables)
    {
        foreach (DataRow dr in table.Rows)
        {
            test addtable = new test()
                {
                    test_id = Convert.ToString(result[0]);
                    test_name = Convert.ToString(dr[1]);
                };
            conn.tests.inInsertOnSubmit(addtable);
        }
    }
}

My issue is that it will work but currently it works only if I create a relationship with the table created from my first button click with my c# code. For eg. let's say I have column names entitled "test_id" and "test_name" from my SQL Server table. I have to then grab that table, put in in my C# code and match the column names. This will be very inconvenient as what I am aiming for is that of the user clicking the button to create a table and then exporting to that table each time they want to read data from some records. I want to eliminate interaction from the database admin. What I want to do it create a table and export an excel file to that same table without having to create some kind of relationship before hand within my code. Additional info: All the individual excel sheets will have the same set of columns each time. Stays the same. Don't know if that helps

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Javy26
  • 375
  • 1
  • 7
  • 22
  • do you mean that excel header do not match always column's name? – McNets Nov 15 '16 at 20:18
  • No what am saying is that any excel file received will always be the same but in the case of this program I am looking how to export an excel file to the database without having to create any previous relationship within my c# code. So in essence am looking how to export an excel file to a MSSQL table – Javy26 Nov 15 '16 at 20:21
  • do you need one table for each excel file or all files will share the same table? – McNets Nov 15 '16 at 20:28
  • One for each. It will be a process like say client A wants to upload a file. They would simply type in the name of the file then click the button in the first function, which would then create the table and then click the other button to export the excel file to the newly created table. Then it would be the same process when another day comes and another file needs to be uploaded. @mcNets – Javy26 Nov 15 '16 at 20:31
  • I'm sorry, are you using LinQ to SQL classes? – McNets Nov 15 '16 at 20:49
  • No am not at the moment @mcNets – Javy26 Nov 15 '16 at 20:52
  • Because you are using `DataClasses1DataContext ` and I think you can get it using the DataSet and a few SqlCommand's. I don't understand what do you mean by 'relationship'. You have a DataSet and can build ÌNSERT`sentences for every row of the file. – McNets Nov 15 '16 at 20:57
  • You really should be using a stored procedure and parameters. Especially since the account has such high permissions that it can create tables. One malformed (maliciously or not) value in that textbox and it's toast. – Nikki9696 Nov 15 '16 at 22:38
  • That said, you can use sql server SEQUENCE to solve issues with id relationships issues. – Nikki9696 Nov 15 '16 at 22:39
  • Oh, and what version of sql server do you have? If you have the right one, SSIS exports can do this really seamlessly (excel to table). That's how I dump excel data to our database. – Nikki9696 Nov 15 '16 at 22:41
  • Oh, and my last idea for now; table valued parameters. Create it, shove it all to a stored proc, then take care of the relationships there. – Nikki9696 Nov 15 '16 at 22:43
  • Thank you. Am aware of that method but It has to be done programatically. – Javy26 Nov 15 '16 at 22:43
  • I think you may have misunderstood in some way. Basically I want an excel file to be sent to a sql table programmatically – Javy26 Nov 15 '16 at 22:44
  • Well, you want DATA to be sent to a sql table. If you create a stored procedure that takes a table-valued parameter, you just create that definition (your excel column names), set the values (in your c# code), and invoke the stored proc. Should accomplish what you're after. Not sure if it helps? (if you actually wanted to store the blob excel file, pls let me know) – Nikki9696 Nov 15 '16 at 22:47
  • Okay I'll give that a shot and get back to you. Thanks you – Javy26 Nov 15 '16 at 22:49
  • Here is a link I found that I hope helps? http://stackoverflow.com/questions/5595353/how-to-pass-table-value-parameters-to-stored-procedure-from-net-code – Nikki9696 Nov 15 '16 at 22:50

1 Answers1

1

I finally got it working, for anyone who might come across this. What I did was just change my file type to a .csv file instead of the excel extension. Excel was giving too much issues. Here is the below function that exports to a MSSQL table on a button click:

 private void button2_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True");
        string filepath = textBox2.Text; //"C:\\Users\\jdavis\\Desktop\\CRF_105402_New Port Maria Rx.csv";
        StreamReader sr = new StreamReader(filepath);
        string line = sr.ReadLine();
        string[] value = line.Split(',');
        DataTable dt = new DataTable();
        DataRow row;
        foreach (string dc in value)
        {
            dt.Columns.Add(new DataColumn(dc));
        }

        while (!sr.EndOfStream)
        {
            value = sr.ReadLine().Split(',');
            if (value.Length == dt.Columns.Count)
            {
                row = dt.NewRow();
                row.ItemArray = value;
                dt.Rows.Add(row);
            }
        }
        SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
        bc.DestinationTableName = textBox1.Text;
        bc.BatchSize = dt.Rows.Count;
        con.Open();
        bc.WriteToServer(dt);
        bc.Close();
        con.Close();
    }
Javy26
  • 375
  • 1
  • 7
  • 22