Update table from excel

SQL Spreads solves some common data management problems for Microsoft SQL Server. It makes it fast and simple to update an SQL table from an Excel spreadsheet. And it gives you the control you need to manage data entered by various users on a collaborative team.
a demo of how to update an SQL table from Excel with SQL Spreads

End users love working in Excel

End users love working in Excel. They know the tool, and they are free to do what they want. That’s the heart of the much-loved Excel application, but also the start of problems for the people taking care of the data. The freedom to add cells and enter “whatever-you-like” values causes huge problems when trying to store and summarize the data in a structured way.

Updating or collecting some “not-available-in-our-systems” data from colleagues is often done by mailing out some Excel file or putting a spreadsheet on a file share.

When users update data in an Excel spreadsheet that should be saved or update in an SQL table, problems like these usually occur:

  • Cells in the spreadsheet can contain invalid data types.
  • There will be problems when users change the layout of the sheet.
  • Difficulties to keep track of previous versions of the Excel spreadsheet.
  • Hard to track who has changed a specific value in a sheet.
  • Troublesome to extract Excel data (with a tool such as SSIS).
  • There can be a delay of several hours between when a user enters the figures and when they appear in the database.

In finance, IT and other fields, structured data is a vital part of the operations. In those fields, you can — literally in minutes — let your end-users update data in structured SQL tables themselves – using Excel. No coding experience or extensive training is necessary.

Here’s information on how you can use SQL Spreads, an Microsoft Excel Add-In, to efficiently and accurately update an SQL Server database from Excel. I will show how to easily bring in your SQL Server tables into Excel for easy updating/management. Then show you how to share the document with your end users and how to keep track of data quality.

How to Update an SQL Table from Excel

To set up an Excel document to work with the data in an SQL Server table, follow these few simple steps:

  1. Download and install the SQL Spreads Excel Add-In.
  2. Go to the SQL Spreads tab in Excel and select Design mode.
  3. A list of databases will appear on the right. Chose the database you are using and select an SQL table to update from Excel.
  4. From the Columns tab you can fine-tune how your table is presented in Excel. You can select the columns you want to update, rearrange them into the order you prefer, and change their names if desired.
  5. When you finished fine-tuning your table, go to the spreadsheet and start updating the data from SQL Server. When you press the Save button the changes will be saved back to your SQL Server table.

There are also several other great benefits of the Designer to easily connect an Excel spreadsheet to a table in SQL Server. For example:

  • Set which columns are editable and which are “read-only”
  • Select which rows in the database are loaded into the Excel spreadsheet
  • Enable Change Tracking and the application will then insert the date and time when a row is changed, as well as the user making the change.
  • Show drop-down lists where the user can select a readable text instead of a key value for columns relating to other tables.

Let your non-technical users update and manage the SQL Server data

After you exit the Design mode you can share your Excel document like any other Excel file. All the settings will follow the document and other users can use your Excel file to update the SQL tables from Excel.

But maybe one of the biggest benefits of SQL Spreads is its ease of use. And the benefits are not only for administrators but also for authorized users throughout your business or enterprise. Non-technical users can use SQL Server-connected Excel documents that you create and share with them. The result will be an accurate and effective collaboration with safeguards including built-in conflict detection.

Assured Data Quality

To get the highest possible quality of data, SQL Spreads uses several methods to guarantee the validity of the entered data:

  • When figures are entered, they are validated against the types of the database columns, and the user receives immediate feedback.
  • Each changed row is tracked in the database to see when a row was changed and by who.
  • A built-in conflict detection system enables safe and easy collaboration.
  • When sharing the document with others, they can be given an Editor role to disable the Design mode to protect the Excel sheet set up that you’ve created.

Automatic Lookup of key values from other tables

Databases contains relations, and a table with keys relating to other tables can be hard to update manually.

When updating a SQL Server table from within Excel, SQL Spreads can lookup those key values in other tables and show drop-down lists where the user can select a readable text instead of a keys value. When the changes are saved to the database, the looked up key will be saved to the database.

Familiar and User-friendly Excel Interface

The data in SQL Server tables can be directly updated from Excel. Users are authenticated using their Windows Login and can only work with the Excel documents for which they are authorized.

Data is automatically validated when users enter their figures through SQL Spreads. And data from other Microsoft Excel documents can be pasted directly into the SQL Server connected documents.

A Low-Stress Solution with High Value to Your Organization

With SQL Spreads, you can:

  • Use Excel to work with data in SQL Server tables.
  • Let non-technical users work with the SQL Server data.
  • Ensure that the entered data is valid.

But more far-reaching benefits can be offered to your business or enterprise by using SQL Spreads. You will immediately see time savings across the board.

  • First, the setup is really fast and simple.
  • Second, when end-users enter data, SQL Spreads will guide them through the right way to enter the data.
  • Third, data owners will have the advantage of being able to easily access centralized data through Excel.
  • Fourth, you can put an end to struggling with importing Excel data using SSIS or maintaining VBA scripts.
  • Lastly, no more troubleshooting and correcting problems created by users altering the spreadsheet.

Those time-consuming processes and frustrations are replaced by SQL Spreads with fast, reliable data management.

Try SQL Spreads First-Hand to Take Control of your SQL Server Data Management

Try SQL Spreads by downloading the new SQL Spreads trial from this page.

There is also a demo video available showing how you can use SQL Spreads to create an Excel document to update the SQL table from Excel.

Editors note: This blog post was originally published for a previous version of SQL Spreads and has been completely revamped and updated for accuracy and comprehensiveness.

Johannes

Johannes Åkesson

Worked in the Business Intelligence industry for the last 15+ years.

Founder of SQL Spreads – the data management
solution to import, update and manage
SQL Server data from within Excel.

There are many ways to do this. I’d recommend something like this, to push data from Excel to SQL Server.

Sub ButtonClick()
'TRUSTED CONNECTION
    On Error GoTo errH
   
    Dim con As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim strPath As String
    Dim intImportRow As Integer
    Dim strFirstName, strLastName As String
   
    Dim server, username, password, table, database As String
   
   
    With Sheets("Sheet1")
           
            server = .TextBox1.Text
            table = .TextBox4.Text
            database = .TextBox5.Text
           
           
            If con.State <> 1 Then
       
                con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
                'con.Open
       
            End If
            'this is the TRUSTED connection string
           
            Set rs.ActiveConnection = con
           
            'delete all records first if checkbox checked
            If .CheckBox1 Then
                con.Execute "delete from tbl_demo"
            End If
       
            'set first row with records to import
            'you could also just loop thru a range if you want.
            intImportRow = 10
           
            Do Until .Cells(intImportRow, 1) = ""
                strFirstName = .Cells(intImportRow, 1)
                strLastName = .Cells(intImportRow, 2)
               
                'insert row into database
                con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
               
                intImportRow = intImportRow + 1
            Loop
           
            MsgBox "Done importing", vbInformation
           
            con.Close
            Set con = Nothing
   
    End With
   
Exit Sub

errH:
    MsgBox Err.Description
End Sub

You can also try this, which uses a Where Clause.

Sub InsertInto()

'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String

'Create a new Connection object
Set cnn = New adodb.Connection

'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PCSQLEXPRESS"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PCSQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes"


'Create a new Command object
Set cmd = New adodb.Command

'Open the Connection to the database
cnn.Open

'Associate the command with the connection
cmd.ActiveConnection = cnn

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText

'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"

'Pass the SQL to the Command object
cmd.CommandText = strSQL


'Execute the bit of SQL to update the database
cmd.Execute

'Close the connection again
cnn.Close

'Remove the objects
Set cmd = Nothing
Set cnn = Nothing

End Sub

  • Remove From My Forums
  • Вопрос

  • Is there way I can update two fields from Excel in SQL table  that we are getting from our Client(Excel file) to our production server every day, we need to update once a a day this data to SQL. 

    Is there way I can set up job for daily basis to update our production table? 

    Thank you for the help!

Ответы

  • https://stackoverflow.com/questions/41920287/automatic-update-from-excel-to-sql-server

    you can use ssis for upadate data from ssis package and schedule job in mssql.

    Keep excel in fixed location so job will not fail. 


    https://social.technet.microsoft.com/wiki/contents/articles/37872.sql-server-installation-on-centos-linux.aspx

    • Помечено в качестве ответа

      12 февраля 2019 г. 7:17

  • you can do it using sql jobs

    2 methods can be used for update

    1. Use a tool like SSIS to get EXcel data to a staging table using data flow task and then update using the table in a execute sql task

    Then call and execute this package from job

    2. Use OPENROWSET based method to do update directly in the query

    like

    UPDATE t
    SET col1 = e.EXcelCol1,
    col2 = e.ExcelCol2
    FROM Table t
    JOIN OPENROWSET(
    
    ‘Microsoft.ACE.OLEDB.12.0’
    
    ,‘Excel 12.0;Database=<Full Excel File Path>;HDR=YES’
    
    ,'Select * from SheetName$') e
    ON e.KeyCol = t.KeyCol
    ..

    where Keycol would be your primary key of the table 


    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    —————————-
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

    • Предложено в качестве ответа
      Xi Jin
      30 августа 2018 г. 2:36
    • Помечено в качестве ответа
      Ed Price — MSFTMicrosoft employee
      12 февраля 2019 г. 7:17

Often when you are working on 2 incompatible systems and try to import data from one to another, excel can be a handy tool. I have used excel plenty of times to generate SQL insert / update statements which I could later execute on the database console. Here is a tutorial if you ever have to use excel to generate SQL statements.

The example below shows a simple insert statement generated from customer data in a table. But you can easily extend this technique to come up with complex query statements.

1. Have your data ready

For our purpose the data is arranged like this:

sql-insert-update-query-from-csv-xls-files-data

As you can see, the data has to be in a tabular format so that you can easily generate the query statements. Often you may have to use lookup formulas to clean up the raw data imported in CSV formats.

2. Using excel operator ‘&’ to generate SQL query

Once the data is ready it is very easy to generate the SQL queries using excel string addition operator – &. For the above tabular structure, the concatenate formula would look like:

="insert into customers values('" &B3 &"','" & C3 & "','"&D3&"');" where B3, C3, D3 refer to above table data.

The final queries will look like:

sql-insert-update-query-from-csv-xls-files-final

There are a few practical ways to improve this:

  • Cleaning up data using countif(), sumif(), if() formulas
  • Using vlookup() or countif() to cross-reference items on one table to another


Share this tip with your colleagues

Excel and Power BI tips - Chandoo.org Newsletter

Get FREE Excel + Power BI Tips

Simple, fun and useful emails, once per week.

Learn & be awesome.




  • 40 Comments




  • Ask a question or say something…




  • Tagged under

    development, howto, Learn Excel, Microsoft Excel Formulas, programming, software, sql, technology, text processing




  • Category:

    Learn Excel, technology

Welcome to Chandoo.org

Thank you so much for visiting. My aim is to make you awesome in Excel & Power BI. I do this by sharing videos, tips, examples and downloads on this website. There are more than 1,000 pages with all things Excel, Power BI, Dashboards & VBA here. Go ahead and spend few minutes to be AWESOME.

Read my story • FREE Excel tips book

Advanced Excel & Dashboards training - Excel School is here

Excel School made me great at work.

5/5

Excel formula list - 100+ examples and howto guide for you

From simple to complex, there is a formula for every occasion. Check out the list now.

Calendars, invoices, trackers and much more. All free, fun and fantastic.

Advanced Pivot Table tricks

Power Query, Data model, DAX, Filters, Slicers, Conditional formats and beautiful charts. It’s all here.

Still on fence about Power BI? In this getting started guide, learn what is Power BI, how to get it and how to create your first report from scratch.

Related Tips

40 Responses to “SQL Queries from Excel”

  1. Leonid says:

    I use this method very often.
    I always use =SUBSTITUTE (ColumnWithText,»‘»,»»»)
    to be sure that potential apostrophe in text columns are doubled as required in SQL.

    • Ankit says:

      Awesome ! I don’t use excel very often so the substitute thing is gold to me 🙂 thanks !

  2. @Leonid.. that is a good technique to use substitute to clean up text apostrophes. thanks

  3. Goal:
    Generate update statement in excel where the columns that can be updated are dynamic
    You want the columns which are not updated to keep the same value
    (or not be overwritten with NULL values with the new generated statement)
    the statement can be applied to multiple rows in excel for the same column headers
    (This is why the ‘$’ exist for the column headers that are being set)

    A1 = First_Name
    B1 = Last_Name
    C1 = Middle_Name


    UPDATE PERSONS «&CHAR(10)&
    » SET 1 = 1 «&CHAR(10)&
    IF(LEN(TRIM($A2))=0,»»,», «&$A$1&» = ‘»&$A2&»‘»&CHAR(10))&
    IF(LEN(TRIM($B2))=0,»»,», «&$B$1&» = ‘»&$B2&»‘»&CHAR(10))&
    IF(LEN(TRIM($C2))=0,»»,», «&$C$1&» = ‘»&$C2&»‘»&CHAR(10))&
    » WHERE name = ‘staticordynamicvalue’ AND gender = ‘staticordynamicvalue’
    «
    Output (if all columns are set):
    UPDATE PERSONS SET 1 = 1,
    First_Name = ‘Joe’,
    Last_Name = ‘ORien’,
    Middle_Name = ‘Richard’
    WHERE age = 28 AND gender = ‘m’

    Output (if only First _Name (A1) is set):
    UPDATE PERSONS SET 1 = 1,
    First_Name = ‘Joe’
    WHERE age = 28 AND gender = ‘m’

  4. Possibly my post above is confusing without the actual table to look at. I will do the same example with the table used here. Instead of an insert statement I will generate an update statement for the columns, Cust_Name, Phone & E-mail
    where we can generate an update statement for any column individually or together. 🙂 I hope this can help.
    =”
    UPDATE table “&CHAR(10)&
    ” SET 1 = 1 “&CHAR(10)&
    IF(LEN(TRIM($A2))=0,”»,”,Cust_Name = ‘”&$B3&”‘”&CHAR(10))&
    IF(LEN(TRIM($B2))=0,”»,”, Phone = ‘”&$C3&”‘”&CHAR(10))&
    IF(LEN(TRIM($C2))=0,”»,”, E-mail = ‘”&$D3&”‘”&CHAR(10))&
    ” WHERE Cust_Name = ’Bill Gates’

  5. Thanks, it has been very useful !
    It saved me at least 30 minutes, and time is the most expensive thing in our world…

  6. Kad says:

    Hey Paul,
    What if any of A2, B2, or C2 is a date field?
    The formula above is taking date as string. Any solution?

    • Smitha says:

      Even I faced the same problem. If any of the above columns are date, it is taken  as string. Any work around for this?

  7. I’ve found the string concatenation method works well.

    At the risk of sounding spammy I would mention that
    if it’s something your are doing regularly it might be worth investigating a tools
    that make it easier, such as QueryCell, an excel add-in I’ve developed.

    It gives you a right click menu option that will produce and then customize insert statements for the selected region of Excel data.

    Cheers
    Sam

    • Hi,
      For inserting the excel data to your SQL table, you can create insert statements in excel file according to your columns.
      then just execute the statements all at once, it will insert the required data to sql server table.
      thanks,

      • Ajay Koli says:

        How…?

  8. Chetan Patil says:

    I tried to generate t-sql insert queries from the above example
    =»insert into values(‘» &A2 &»‘,'» & B2& «‘);»
    but it generates on one record instead of all records from excel sheet.
    I’m using Excel 2003 and the excel sheet contains 922 records.

  9. Most data bases can generate DDL for any object but not a lot of them allow generation of INSERT statements for the table data.
    The workaround is to make use of ETL Tools for transferring data across servers. However, there exists a need to generate INSERT statements from the tables for porting data.
    Simplest example is when small or large amount of data needs to be taken out on a removable storage media and copied to a remote location, INSERT..VALUES statements come handy.

    There is a number of scripts available to perform this data transformation task. The problem with those scripts that all of them database specific and they do not work with textiles

    Advanced ETL processor can generate Insert scripts from any data source including text files
    http://www.dbsoftlab.com/generating-insert-statements.html

  10. B.N.Prabhu says:

    Super Aiticle. Thanks for this post.

  11. Archana says:

    Hi ,
    i need a sql query to update a DB in excel 2010..
    i have the query(SQL) for insert in excel as ,
    =»insert into customers values(‘» &B3 &»‘,'» & C3 & «‘,'»&D3&»‘);»

    similarly i need q sql query for update in excel

  12. i want clear formulas only for insert,delete,update,select

  13. Ankit Mahendru says:

    Hi !
    I would like to thank you so much ! This trick saves me a  lot of time. Thank you so much. Really appreciate it !

     
    -Ankit

  14. You may like to take advantage of this unique tool ‘Excel to Database’. 
    (free for 60 days)http://leansoftware.net The Excel-to-Database utility enables you to validate and transfer data from Microsoft Excel or text file to a database table or stored procedure process. Any text data can be pasted into the application, this may be from another Excel sheet or from text files such as CSV format. SQL Server, Access, MySQL, FoxPro .. Application features Some unique features of Excel to Database include: ?Easy to use color coded/traffic light data validation ?Data is validated as soon it is typed or pasted into Excel ?Upload Excel data to a table or stored procedure process ?Allow default values ?Mandatory/must have fields can be specified ?Allow user friendly column names ?Allow excel formula / calculated fields ?Multiple database type support: Microsoft SQL Server, Access, MySQL and others (to be tested) ?Supports Custom SQL scripts, with SQL/Excel merge fields ?Database validation checks ensure you comply with any rules defined within the database ?Multiple Task configuration ?For co-operative use, Tasks can be shared across a network ?Task configuration is password protected http://leansoftware.net 

  15. Manoraj says:

    Its works fine for single record.
    I want to update 1000 records in DB. Can you help me.

  16. Excel database tasks 2.3 (EDT)
    you can now load directly from any source into Excel, validate and upload to most SQL database platforms including SQL Server with automatic transaction wrapping.
    You can also use EDT as a multi-user application by easily designing your own Edit data tasks and deploying EDT on your users workstations.
    Automatically creates UPDATE/INSERT statements based on the primary key.  Default SQL can be modified as you require.
    Makes the best use if Excel power — formatting, formula, validation, conditional formatting..  without creating any problematic spreadsheets!
    Release details on the blog:
    http://leansoftware.net/forum/en-us/blog.aspx
    Thanks for the interest
    Richard

  17. Usman says:

    Thanks for the valueable information, it really help me alot.

     
    Thanks again.

  18. Laercio says:

    As I do with a field of type date?
    = «UPDATE SET business datetime =» & «‘» & A2 & «‘ WHERE ID =» & B2 & «»
    the date is not 03/10/2012 is 41246. Even putting quotes …

  19. Elaein says:

    Please show how to do it properly with dates as well as when those dates are empty. Thanks!

  20. mahesh.S says:

    In a separate column make the date to Text using below formula
    =TEXT(C2,»mm/dd/yyyy») Then Refer this text column in your update statement

  21. cjb says:

    Great post saved me a a load of time on a task i had to complete

  22. sql010 says:

    thanks for sharing article… helpful!

  23. Pooja says:

    Thanks 🙂

  24. […] Excel formula used – http://chandoo.org/wp/2008/09/22/sql-insert-update-statements-from-csv-files/ […]

  25. HSoomro says:

    If any one can help me out with following.
    I want to know a SQL query of below excel formula:
    =LOOKUP(0,-SEARCH(LEFT(F2,LEN($B$2:$B$100))+0,$B$2:$B$100),$A$2:$A$100)

    Excel data is as below;
    Name Codes
    names1 992
    names2 57
    names3 856
    names4 297
    names5 63

    if there is a number (29756789) then it should search in sql by taking the prefix of number (297) from (29756789) and return the name field (name4).
    Codes can be of two digit or three.

    Thanks

  26. Victor R Udeshi says:

    =»INSERT INTO table VALUES (» &A3 &»,'» & B3 & «‘,'»&C3&»‘,'» & D3 & «‘,'» & E3 & «‘,» & F3 & «,» & G3 & «,» & H3 & «,'» & I3 & «‘,» & J3 & «);»

    B3 has date data that looks like 9/22/17 but with the formula above b3 is coming out as 43000?

    how do i fix that?

  27. Mr.Shan says:

    I just want to insert the Excel records in Sql table without Visiting SQL.
    basically i m just want to run a command in Excel Only.
    Help Me..plz..?

  28. Danyal Hussain says:

    Hi I have a question maybe you guys have an answer for me

    =»insert into customers values(‘» &B3 &»‘,'» & C3 & «‘,'»&D3&»‘);» where B3, C3, D3 refer to above table data.

    the above technique works but is there a way to write it so it takes a range instead of individual columns. because I have an extremely wide table

    =»insert into customers values(B3:D3);» where B3, C3, D3 refer to above table data.

  29. Qadir Bux says:

    Awsome

  30. Bhagwat says:

    Its Great Effort to help everyone who working with excel.

  31. Ed says:

    Thanks for the mini-tutorial on SQL from Excel. Didi it several years ago, but couldn’t remember the syntax! All the dialogue was really helpful as well!

Leave a Reply

Introduction

I got the requirement to update the database table using the excel sheet data provided by the end-user. End-user will provide different database table names and the corresponding excel data, we need to upload that particular excel data into that corresponding database provided by the end-user.

Handling the field level validations i.e, the field order of that particular table with the field order of the excel data.

Here I am going to explain the step by step procedure to update the database table based on the excel data dynamically.

Step 1:

Go to the T-code SE 38.

Step 2:

Give the program as “ZR_DYNAMIC_TABLE_UPDATE_EXCEL” and click on create button a pop up should be displayed, where we need to provide the title asDynamically Update The Excel Data To Database Table” and type as “Executable Program”, Then click on Save button a pop up will be displayed.

Step 3: Need to provide the package name and click on the continue button.

Here we need to write the source code.

SOURCE CODE:

REPORT zr_dynamic_table_update_excel NO STANDARD PAGE HEADING.
*** --- Data Declarations
DATA:lt_excel       TYPE TABLE OF alsmex_tabline,
     lt_dref        TYPE REF TO data,
     ls_dref        TYPE REF TO data,
     lv_col         TYPE i,
     lo_alv         TYPE REF TO cl_salv_table,
     lt_table_filds TYPE TABLE OF dfies.
*** --- Field Symbols
FIELD-SYMBOLS : <fs_table> TYPE any .
FIELD-SYMBOLS : <ft_table> TYPE STANDARD TABLE.
FIELD-SYMBOLS : <dyn_field> .

*** --- Selection screen designing
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE TEXT-001.
PARAMETERS:p_file  TYPE rlgrap-filename OBLIGATORY,
           p_table TYPE dd02l-tabname OBLIGATORY,
           p_test  AS CHECKBOX DEFAULT abap_true.
SELECTION-SCREEN END OF BLOCK b1.

*** --- value request for p_file
AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
  CALL FUNCTION 'F4_FILENAME'
    IMPORTING
      file_name = p_file.
*** --- START-OF-SELECTION
START-OF-SELECTION.
*create OBJECT lr_descr.
*** --- Assigning fields symbols for Tables
  CREATE DATA lt_dref TYPE TABLE OF (p_table).
  CREATE DATA ls_dref TYPE (p_table).
*** --- Assign field symbol with table type of DDIC
  ASSIGN lt_dref->* TO <ft_table>.
*** --- Assign field symbol with Structure type of DDIC
  ASSIGN ls_dref->* TO <fs_table>.
*** --- Call the Function module ALSM_EXCEL_TO_INTERNAL_TABLE
  CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'
    EXPORTING
      filename                = p_file
      i_begin_col             = 1
      i_begin_row             = 1
      i_end_col               = 99
      i_end_row               = 999999
    TABLES
      intern                  = lt_excel
    EXCEPTIONS
      inconsistent_parameters = 1
      upload_ole              = 2
      OTHERS                  = 3.
  IF sy-subrc EQ 0.
*** --- Sort
    SORT lt_excel BY row.

    LOOP AT lt_excel INTO DATA(ls_excel).

*** --- Adding count to skip the mapping for MANDT field
      lv_col = ls_excel-col + 1.
      ASSIGN COMPONENT lv_col OF STRUCTURE <fs_table> TO <dyn_field>.
      IF sy-subrc = 0.
***-- Compare Excel sheet column data and Dynamic table fields
            IF ls_excel-row = 1.
              CALL FUNCTION 'DDIF_FIELDINFO_GET'
                EXPORTING
                  tabname        = p_table
                TABLES
                  dfies_tab      = lt_table_filds
                EXCEPTIONS
                  not_found      = 1
                  internal_error = 2
                  OTHERS         = 3.
              READ TABLE lt_table_filds INTO DATA(ls_table_fields) INDEX lv_col.
              IF sy-subrc = 0.
                IF ls_table_fields-fieldname NE ls_excel-value.
                  WRITE: 'Excel sheet data and Dynamic table fields are not matching'.
                  EXIT.
                ENDIF.
              ENDIF.
            ELSE.
              <dyn_field> = ls_excel-value.
            ENDIF.
      ENDIF.
      IF ls_excel-row GT 1.
        AT END OF row.
          APPEND <fs_table> TO <ft_table>.
          CLEAR <fs_table>.
        ENDAT.
      ENDIF.
    ENDLOOP.

    IF <ft_table> IS NOT INITIAL.
      IF p_test IS INITIAL.
*** --- Modify
        MODIFY (p_table) FROM TABLE <ft_table>.
        IF sy-subrc EQ 0.
          COMMIT WORK.
          DATA(lv_lines) = lines( <ft_table> ).
          WRITE: TEXT-002,lv_lines.
        ELSE.
          ROLLBACK WORK.
          MESSAGE TEXT-003 TYPE 'E' DISPLAY LIKE 'I'.
        ENDIF.
      ELSE.
*** --- Factory Method
        cl_salv_table=>factory(
          IMPORTING
            r_salv_table   =  lo_alv   " Basis Class Simple ALV Tables
          CHANGING
            t_table        = <ft_table>
        ).
*** --- Display
        lo_alv->display( ).
      ENDIF.
    ENDIF.
  ENDIF.

Step 4:

Before uploading the data, check the table entries.

Step 5:

Provide the file name, table name and check the test checkbox click on execute button.

Negative Test Case:

Uploading the excel with end-user preferred columns order, irrespective of the corresponding table fields.

Output:

We are validating the particular table fields order with the end-user provided excel fields order and throwing the error if both the fields differ.

Positive Test Case

Output:

The excel data will be as like as below.

Step 6:

Provide the file name, and table name and Uncheck the Test checkbox, click on the execute button.

Output:

Step 7:

Go to the T-code (SE16N), provide the table name as “ZMARA_TABLE1″, and click on execute button the updated data will be reflected the database table.

Conclusion:

By following the above steps, we have successfully updated the database table with the excel data.

Hope this will help.

Thanks for reading.

Понравилась статья? Поделить с друзьями:
  • Update list in excel
  • Update excel with sql
  • Unhiding all sheets in excel
  • Update excel cells vba excel
  • Unhiding all columns in excel