Saturday 21 September 2019

How to export one table or sheet to multiple tables or sheets

If you have one excel sheet or table and you want to export it to multiple sheets or tables use the following steps:

  1. Specify the column -tablesNamesColumn- you want its data to be the names of the tables/sheets 
  2. import the main sheet to MSSQL 
  3. Select distinct values from the tablesNamesColumn
  4. Create a table and name it "TablesNames":                                                                                       CREATE TABLE [dbo].[TablesNames](
           [id] [int] IDENTITY(1,1) PRIMARY KEY,
           [Table_Name] [nvarchar](255) NOT NULL,
    )   
  5. insert the tables names in the table which contains the tables names                                               insert into TablesNames
    SELECT distinct tablesNamesColumn  
    FROM [AllSheets]
  6. Now you need to loop inside the tables names and create tables in the same format         
    DECLARE @LoopCounter INT , @MaxTablesNamesId INT,
            @TableName NVARCHAR(100)
    SELECT @LoopCounter = 0 , @MaxTablesNamesId = count(*)
    FROM TablesNames

    WHILE ( @LoopCounter IS NOT NULL
            AND  @LoopCounter <= @MaxTablesNamesId)
    BEGIN
       SELECT @TableName = Table_Name FROM TablesNames
       WHERE id = @LoopCounter
      -- PRINT @TableName 
       SELECT @LoopCounter  = min(id) FROM TablesNames
       WHERE id > @LoopCounter
      
    declare @q nvarchar(max) = '
    drop table ['+@TableName+'];
    SELECT * INTO  ['+@TableName+']
    FROM [delme]
    WHERE Institution = N'''+ @TableName +''';' 
    exec (@q)
    END
  7. Use the following steps to export the data to Excel 97-2003 file, because I tried Excel 2010 and 2016, the only one works fine is 97-2003  

1 comment: