How to Summarize and Transpose Cross Tables of Indefinite Number of Columns into a Fullycategorized Cross Table
Problem description
The Excel file book1.xlsx contains data as shown below. There are 4 tables of 5 rows and 5 columns. The first rows in columns 24 are numbers representing the vertical axis. Rows 24 in the first column in each table contains numbers, too, which represent horizontal axis.
We are trying to summarize data in the workbook by adding up numbers with same coordinates. And then list all vertical coordinates and horizontal coordinates and their corresponding aggregate values. Below is the expected result:
The problem involves retrieving data from a certain area in an Excel file, grouping & aggregation, and data transposition.
Directions
1. Write the following script:
A 
B 

1 
=file("E:/work/ book1.xlsx") 

2 
for 4 
>r=(A21)\2*7+1 
3 
>c=(1A2%2)*7+1 

4 
=to(c,c+4).("#"/~).concat(",") 

5 
=A1.xlsimport@t(${B4};1,r:r+4) 

6 
=B5.pivot@r(#1;y,value) 

7 
>B1=B1B6 

8 
=B1.groups(#1,y;sum(value):value) 

9 
=A8.pivot(#1;y,value) 

10 
=file("E:/work/book2.xlsx").xlsexport@t(A9) 
A1 Define file book1.xlsx.
A2 Loop through the four tables to read data from them.
B2 Get the number (r) of start row for the current table.
B3 Get the number (c) of start column for the current table.
B4 Get the string of all column numbers of the current table. For example, the string for table 2 is #8,#9,#10,#11,#12.
B5 Import rows from r to r+4 in columns specified by numbers in B4 from book1.xlsx. @t option enables reading the first row as column headers.
B6 Perform rowtocolumn transposition on the table read by B5; @r enables a columntorow transposition. Data is grouped by column 1 and new column numbers are set as y and value.
B7 Concatenate each transposed table sequence to B1.
A8 Group B1’s data by column 1 and y, sum values in each group, and name the totals column value.
A9 Perform rowtocolumn transposition on A8’s grouped and summarized data. Group the data by column 1, and make y values new column names and value values new column values.
A10 Export A9’s result to book2.xlsx. @t option enables outputting the first row as column headers.
2. Run program and then we can view the newlygenerated book2.xlsx in work directly.