简体   繁体   中英

How to convert datatype before Importing Excel file to Sql database

Here I have this Import from excel file to sql database class. It was working correctly till now but as my excel file cells are all strings type , So when Importing , the datatype does not match as sql database. How to convert it to their respective datatype before importing?

public static void ImportToSql(string excelfilepath)
    {

        string myexceldataquery = "select LocalSKU,ItemName, QOH,Price,Discontinued,Barcode,Integer2,Integer3,SalePrice,SaleOn,Price2 from [sheet1$]";

        try
        {
            string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + excelfilepath + "; Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=2\"";

           string ssqlconnectionstring = "Data Source=DELL\\SQLSERVER1;Trusted_Connection=True;DATABASE=Test;CONNECTION RESET=FALSE";
            SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);

            //series of commands to bulk copy data from the excel file into our sql table
            OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
            OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);

            oledbconn.Open();

            OleDbDataReader dr = oledbcmd.ExecuteReader();

            SqlCommand sqlcmd = new SqlCommand(@"MERGE Inventory AS target
                          USING (select LocalSKU,ItemName, QOH,Price,Discontinued,Barcode,Integer2,Integer3,SalePrice,SaleOn,Price2 from @source)  as source
                          ON (source.LocalSKU = target.LocalSKU)
                         WHEN MATCHED THEN
                          UPDATE SET ItemName=source.ItemName,Price=source.Price,Discontinued=source.Discontinued,Barcode=source.Barcode,Integer2=source.Integer2,Integer3 = source.QOH,SalePrice=source.SalePrice,SaleOn=source.SaleOn,Price2=source.Price2;", sqlconn);


            SqlParameter param;
            param = sqlcmd.Parameters.AddWithValue("@source",dr);
            param.SqlDbType = SqlDbType.Structured;
            param.TypeName = "dbo.InventoryType";

            sqlconn.Open();
            sqlcmd.ExecuteNonQuery();
            sqlconn.Close();

            while (dr.Read())
            {

            }
            oledbconn.Close();
            Console.WriteLine(".xlsx file imported succssessfully into database.");
        }

The easiest thing to do would be to convert them in your SQL statement by using CAST :

SqlCommand sqlcmd = new SqlCommand(
  @"MERGE Inventory AS target
    USING (select LocalSKU, ItemName, QOH = CAST(QOH AS int)
    , Price = CAST(Price AS decimal(10,2)), Discontinued = CAST(Discontinued AS bit)
    , Barcode, Integer2 = CAST(Integer2 AS int)
    , Integer3 = CAST(Integer3 AS int), SalePrice = CAST(SalePrice AS decimal(10,2))
    , SaleOn, Price2 = CAST(Price2 AS decimal(10,2)) from @source)  as source
    ON (source.LocalSKU = target.LocalSKU)
    WHEN MATCHED THEN
    UPDATE (. . . )

I'm guessing on some of the conversions, but you get the idea. You'll need to make sure that the data in the spreadsheet all match the datatypes you want to convert them to, as one mistake will cause the whole statement to fail. Something more robust will take a lot more code.

First browse the excel file and put data in datagrid and then read datagrid row one by one. i give you 2 function for that. one is browse the excel file and put data in datagrid and second one is read datagrid and put record in database

Excel Export Function

private void export_btn_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application ExcelApp =
                      new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook ExcelBook;
            Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;

            int i = 0;
            int j = 0;

            //create object of excel
            ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
            ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
            //export header
            for (i = 1; i <= this.dataGridView1.Columns.Count; i++)
            {
                ExcelSheet.Cells[1, i] = this.dataGridView1.Columns[i - 1].HeaderText;
            }

            //export data
            for (i = 1; i <= this.dataGridView1.RowCount; i++)
            {
                for (j = 1; j <= dataGridView1.Columns.Count; j++)
                {
                    ExcelSheet.Cells[i + 1, j] = dataGridView1.Rows[i - 1].Cells[j - 1].Value;
                }
            }

            ExcelApp.Visible = true;

            //set font Khmer OS System to data range
            Microsoft.Office.Interop.Excel.Range myRange = ExcelSheet.get_Range(
                                      ExcelSheet.Cells[1, 1],
                                      ExcelSheet.Cells[this.dataGridView1.RowCount + 1,
                                      this.dataGridView1.Columns.Count]);
            Microsoft.Office.Interop.Excel.Font x = myRange.Font;
            x.Name = "Arial";
            x.Size = 10;

            //set bold font to column header
            myRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, 1],
                                     ExcelSheet.Cells[1, this.dataGridView1.Columns.Count]);
            x = myRange.Font;
            x.Bold = true;
            //autofit all columns
            myRange.EntireColumn.AutoFit();


            ExcelApp.ActiveWorkbook.SaveCopyAs("E:\\reports.xlsx");
            ExcelApp.ActiveWorkbook.Saved = true;
            ExcelApp.Quit();
            MessageBox.Show("Excel file created,you can find the file E:\\reports.xlsx");
            //
            ExcelSheet = null;
            ExcelBook = null;
            ExcelApp = null;            
        }

  1. Read Datagrid

     public void readDataGrid() { for (int i = 0; i < dataGridView1.Rows.Count; i++) { try { //Here read one by one cell and convert it into your required datatype and store it in String rowcell1 = dataGridView1.Rows[i].Cells[0].Value.ToString(); } catch (Exception err) { } count++; } } 

I this is help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM