cancel
Showing results for 
Search instead for 
Did you mean: 
Reply

Create Excel table with dynamic column names and populate quickly Office Scripts/GraphAPI

Hello,

 

my use case is creating students lists with columns that a user (teacher) specified in a PowerApp and place the file in the user's onedrive.

 

I have everything working, but populating is very slow:

I pass class name, array of column names and an array of objects with all the student data to PowerAutomate.

I then create a new excel file with file of an empty excel file content stored in a compose action.

 

Then I create the table (named after the class) with the column names from the array.

I can then loop through the array of objects and add rows. But this takes about a second per row which is too long.

 

So, I am looking for a faster way (probably using Office Scripts of Graph API)

Creating the table with the Excel connector works reasonably fine.

I would would just like a script that will accept the json and then populate the excel table.

 

It should only be a few lines of code, but none of the videos I've watched really helped me.

 

Thank you guys!

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.
1 ACCEPTED SOLUTION

Accepted Solutions

Hmm, it looks like it wasn't able to get the table. Have you confirmed that the table was successfully created through the previous action? We could also try creating the table in the script itself:

 

 

function main(workbook: ExcelScript.Workbook, worksheetName: string, tableRange: string, tableName: string, dataJson: string) {
    let data: object[] = JSON.parse(dataJson);
    // Create table, using object keys as headers
    // IMPORTANT: table range must match the number of columns
    let table = workbook.getWorksheet(worksheetName).addTable(tableRange, false);
    table.setName(tableName);
    table.getHeaderRowRange().setValues([Object.keys(data[0])]);

    // Insert a row for each object
    data.forEach(obj => {
        // Insert new row at end of the table
        let values: (string | number | boolean)[] = Object.values(obj);
        table.addRow(-1, values);
    });

    // Sort and autofit
    table.getSort().apply([{ key: 0, ascending: true }]);
    table.getRange().getFormat().autofitColumns();
}

 

 

Because the table range should match the number of columns, based on the sample data you provided, the range should be A1:BM1. Does that work?

View solution in original post

16 REPLIES 16

@schwibach Can you upload a screenshot of what your current flow looks like?

@creativeopinion 

Here is a screenshot of the flow. It works as it should, but it takes much too long, so I would like to replace the apply_to_each loop with calling an office script that I will send the array of objects with the content.

If the script accepts the table name and the column names as separate parameters, then I would replace the create table step, too.

schwibach_0-1694327680433.png

 

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

I actually just had a quick fix for my use case.... I just turned on concurrency control and set it to max.

Now, it performs fast enough for me.

However, I see great potential in office scripts.

So, if somebody has a template for a working script that accomplishes that, I would be highly interested.

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

Unfortunately, it's not an ideal fix for me....

The lists are not in alphabetical order when the Concurrency Control allows multiple inserts in parallel.

 

So, I'll have to find a solution with a script to pass on the array of objects to the excel file. 😞

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

Hi @schwibach - you could try the following script:

function main(workbook: ExcelScript.Workbook, tableName: string, dataJson: string) {
    let table = workbook.getTable(tableName);
    let data: (string | number | boolean)[][] = JSON.parse(dataJson);
    data.forEach(values => {
        // Insert new row at end of the table
        table.addRow(-1, values);
    });
}

Depending on how your data is formatted, you might have to adjust this script to make sure the data can be parsed into the appropriate type. If you'd like to share some sample data, I can help with that.

 

Let me know if you have any questions!

@MichelleRanMSFT 
Thank you

 

schwibach_0-1694468467473.png

 

I created the script

 

Here is the JSON Array with a dummy object. Except for nbg_id all all values could also be null (even if selected to be added to the Excel table)


[
    {
      "Abwesenheiten_Empfänger_Anrede": "Herr",
      "Abwesenheiten_Empfänger_EMail": "aaaa@bnbb.net",
      "Abwesenheiten_Empfänger_Nachname": null,
      "Alter": 22,
      "Ausbilder_Nachname": "TestNachname",
      "Ausbilder_Vornamen": "TestVorname",
      "Ausbildungsberuf": "TestBeruf",
      "Austrittsdatum": "2024-12-01",
      "Bemerkung": "TestBemerkung",
      "Bemerkung_Mittelschule": "TestBemerkung2",
      "Betrieb_EMail": "Email@Betrieb.de",
      "Betrieb_Firma": "Betrieb AG",
      "Betrieb_Hausnummer": "1",
      "Betrieb_Kürzel": "ABCD",
      "Betrieb_Mobil":"01234/34670",
      "Betrieb_Ort": "Testort",
      "Betrieb_PLZ": "99999",
      "Betrieb_Straße": "Teststraße",
      "Betrieb_Telefon": "09000 958-0",
      "Direktorat": "B15",
      "Doppelmeldung_Direktorat": "B14",
      "Doppelmeldung_Klasse": "10a",
      "Doppelmeldung_Klassenart": "Fachklasse",
      "Eintrittsdatum": "01.06.2021",
      "Gastschulgenehmigung": "0",
      "Gastschülerart": "Gastschüler (Fachsprengel)",
      "Gastschülerberechtigung": "Bay. GSch, (n. Umschl.)",
      "Geburtsdatum": "01.01.2001",
      "Geschlecht": "Männlich",
      "Hauptansprechpartner_Anrede": "Frau",
      "Hauptansprechpartner_EMail": "email@email.net",
      "Hauptansprechpartner_Geschlecht": "weiblich",
      "Hauptansprechpartner_Hausnummer": "1",
      "Hauptansprechpartner_Mobil": "12345/3457",
      "Hauptansprechpartner_Nachname": "TestNachname",
      "Hauptansprechpartner_Ort": "TestOrt",
      "Hauptansprechpartner_PLZ": "12345",
      "Hauptansprechpartner_Personentyp": "Mutter",
      "Hauptansprechpartner_Straße": "Teststraße",
      "Hauptansprechpartner_Telefon": "12346/3423",
      "Hauptansprechpartner_Vornamen": "Sandra",
      "Klasse": "10b",
      "M365_EMail": "aaa@contoso.com",
      "Merker_AP": "AP",
      "Merker_Alle": "JOA alt1",
      "Merker_H": "H",
      "Merker_SZ": "SZ",
      "Merker_Z": "Z",
      "Nachname": "Muster",
      "Religionszugehörigkeit": "römisch-katholisch",
      "Rufname": "Max",
      "Schulnummer": "6999",
      "Schüler_EMail": "email2@gmx.de",
      "Schüler_Hausnummer": "3",
      "Schüler_Mobil": "017634974587234",
      "Schüler_Ort": "Nürnberg  ",
      "Schüler_PLZ": "90489",
      "Schüler_Straße": "Hauptmarkt",
      "Schüler_Telefon": "012489453480 342",
      "Stellung_im_Beruf": "mit Ausbildungsvertrag",
      "Teilnahme_Religion_Ethik": "EV",
      "Vorbildung_schulisch": "Quali. Mittelschulabschluss",
      "Vornamen": "Max",
      "Vorzeitige_Prüfung": "0",
      "nbg_id": "e74KsckNe+nerTESTNBGID/7yytQzmcVlsdfwefqA="
    }]

I get this error. 
schwibach_1-1694468590216.png

 

 

 

 

I already found a script to do auto width of the columns afterwards.
When we manage to add the data I would like to order the table ascending, using the first column in the table.
 
Thank you so much for your help!
__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

How about this?

function main(workbook: ExcelScript.Workbook, tableName: string, dataJson: string) {
    let table = workbook.getTable(tableName);
    let data: object[] = JSON.parse(dataJson);
    data.forEach(obj => {
        // Insert new row at end of the table
        let values: (string | number | boolean)[] = Object.values(obj);
        table.addRow(-1, values);
    });
    table.getSort().apply([{ key: 0, ascending: true }]);
    table.getRange().getFormat().autofitColumns();
}

I get this error:

schwibach_0-1694493249920.png

 

Before running the script, I use the file content of an empty excel file to create an new one:

schwibach_1-1694493311633.png

 

 

Then I create the table with the columns using the regular connector:

schwibach_2-1694493350930.png


If it makes things easier, I could leave out the last step and we create a new table with a table name that we pass to the script and then column names, that we pass in an array to excel.

 

 

 

 

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

Could you share the script that's causing the error? The one I shared earlier doesn't call console.error so I'm not sure where the error would be coming from. Additionally, how many columns does the table you create through the regular connector have?

@MichelleRanMSFT  Sorry, I sent the wrong error message.

schwibach_0-1694537519762.png

 

 

 

This is the one I get when using your script.

I tried to play around with it myself.

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

Hmm, it looks like it wasn't able to get the table. Have you confirmed that the table was successfully created through the previous action? We could also try creating the table in the script itself:

 

 

function main(workbook: ExcelScript.Workbook, worksheetName: string, tableRange: string, tableName: string, dataJson: string) {
    let data: object[] = JSON.parse(dataJson);
    // Create table, using object keys as headers
    // IMPORTANT: table range must match the number of columns
    let table = workbook.getWorksheet(worksheetName).addTable(tableRange, false);
    table.setName(tableName);
    table.getHeaderRowRange().setValues([Object.keys(data[0])]);

    // Insert a row for each object
    data.forEach(obj => {
        // Insert new row at end of the table
        let values: (string | number | boolean)[] = Object.values(obj);
        table.addRow(-1, values);
    });

    // Sort and autofit
    table.getSort().apply([{ key: 0, ascending: true }]);
    table.getRange().getFormat().autofitColumns();
}

 

 

Because the table range should match the number of columns, based on the sample data you provided, the range should be A1:BM1. Does that work?

schwibach_0-1694545341594.png




The table gets created with the action. (When I use the add rows action, the table works fine, too)

I tried the new script without creating a table, just the newly created file and I get this error:

We were unable to run the script. Please try again.
Runtime error: Line 7: Cannot read properties of undefined (reading 'addRow')
clientRequestId: e5ddd41b-5a8c-4fdc-9832-1674612f80f5

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

When you say the "new script", do you mean the one I shared in the most recent post? The newest version I shared shouldn't be calling addRow on line 7.

 

Also, to make sure I understand what you're trying to accomplish: the table you shared a screenshot of only has 3 columns. Is that intended, or did you want a column for every key in the object? I was assuming it was the latter, but if not, the script would have to be modified.

Oh dear... sorry for the confusion..

I think I forgot to save the script.

This is the error I get now:
We were unable to run the script. Please try again.
Office JS error: Line 5: {"message":"Das Argument ist ungültig, fehlt oder hat ein falsches Format.","code":"InvalidArgument","type":"Workbook","method":"getWorksheet","line":5}
clientRequestId: ea39e5b3-e2b7-4db8-8fe0-c0d0e51b1384


About the creation of the table: I wanted to pass on the json array of objects and have the script pick the values that match the column names. (The excel add row action does exactly that)

However, I could also use a select action to make a json array of objects that will only contain the columns needed. That would be fine, too. Whichever is easiest.

With the ShowColums and JSON function in PowerApps it's just as quick. 

__________________________________
Please mark topics as solved if they are and give kudos to make people happy 🙂
Always interested to hear about solutions/problems in the education sector.

I see - so, two things here. First, when you edit a script that's being used in a flow, you might want to re-select it in the run script action to make sure the parameters update. In the latest version of the script I shared, I added a parameter for the worksheet name and I think it wasn't being picked up.

 

Second, if you only want to take specific properties from the objects, I think the most performant way to do this would be to use the select action to modify the JSON array. You can then pass the modified JSON array into the script from above. If it's still not working, you can debug it by using console.log (instead of console.error).

 

Let me know if that helps, or if you have any questions!

ahhhh! this thing about concurrency I didn't think about made me crazy! thanks for pointing this out!

Helpful resources

Announcements

Community will be READ ONLY July 16th, 5p PDT -July 22nd

Dear Community Members,   We'd like to let you know of an upcoming change to the community platform: starting July 16th, the platform will transition to a READ ONLY mode until July 22nd.   During this period, members will not be able to Kudo, Comment, or Reply to any posts.   On July 22nd, please be on the lookout for a message sent to the email address registered on your community profile. This email is crucial as it will contain your unique code and link to register for the new platform encompassing all of the communities.   What to Expect in the New Community: A more unified experience where all products, including Power Apps, Power Automate, Copilot Studio, and Power Pages, will be accessible from one community.Community Blogs that you can syndicate and link to for automatic updates. We appreciate your understanding and cooperation during this transition. Stay tuned for the exciting new features and a seamless community experience ahead!

Summer of Solutions | Week 4 Results | Winners will be posted on July 24th

We are excited to announce the Summer of Solutions Challenge!    This challenge is kicking off on Monday, June 17th and will run for (4) weeks.  The challenge is open to all Power Platform (Power Apps, Power Automate, Copilot Studio & Power Pages) community members. We invite you to participate in a quest to provide solutions to as many questions as you can. Answers can be provided in all the communities.    Entry Period: This Challenge will consist of four weekly Entry Periods as follows (each an “Entry Period”)   - 12:00 a.m. PT on June 17, 2024 – 11:59 p.m. PT on June 23, 2024 - 12:00 a.m. PT on June 24, 2024 – 11:59 p.m. PT on June 30, 2024 - 12:00 a.m. PT on July 1, 2024 – 11:59 p.m. PT on July 7, 2024 - 12:00 a.m. PT on July 8, 2024 – 11:59 p.m. PT on July 14, 2024   Entries will be eligible for the Entry Period in which they are received and will not carryover to subsequent weekly entry periods.  You must enter into each weekly Entry Period separately.   How to Enter: We invite you to participate in a quest to provide "Accepted Solutions" to as many questions as you can. Answers can be provided in all the communities. Users must provide a solution which can be an “Accepted Solution” in the Forums in all of the communities and there are no limits to the number of “Accepted Solutions” that a member can provide for entries in this challenge, but each entry must be substantially unique and different.    Winner Selection and Prizes: At the end of each week, we will list the top ten (10) Community users which will consist of: 5 Community Members & 5 Super Users and they will advance to the final drawing. We will post each week in the News & Announcements the top 10 Solution providers.  At the end of the challenge, we will add all of the top 10 weekly names and enter them into a random drawing.  Then we will randomly select ten (10) winners (5 Community Members & 5 Super Users) from among all eligible entrants received across all weekly Entry Periods to receive the prize listed below. If a winner declines, we will draw again at random for the next winner.  A user will only be able to win once overall. If they are drawn multiple times, another user will be drawn at random.  Individuals will be contacted before the announcement with the opportunity to claim or deny the prize.  Once all of the winners have been notified, we will post in the News & Announcements of each community with the list of winners.   Each winner will receive one (1) Pass to the Power Platform Conference in Las Vegas, Sep. 18-20, 2024 ($1800 value). NOTE: Prize is for conference attendance only and any other costs such as airfare, lodging, transportation, and food are the sole responsibility of the winner. Tickets are not transferable to any other party or to next year’s event.   ** PLEASE SEE THE ATTACHED RULES for this CHALLENGE**   Week 1 Results: Congratulations to the Week 1 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge.   Community MembersNumber SolutionsSuper UsersNumber Solutions Deenuji 9 @NathanAlvares24  17 @Anil_g  7 @ManishSolanki  13 @eetuRobo  5 @David_MA  10 @VishnuReddy1997  5 @SpongYe  9JhonatanOB19932 (tie) @Nived_Nambiar  8 @maltie  2 (tie)   @PA-Noob  2 (tie)   @LukeMcG  2 (tie)   @tgut03  2 (tie)       Week 2 Results: Congratulations to the Week 2 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 2: Community MembersSolutionsSuper UsersSolutionsPower Automate  @Deenuji  12@ManishSolanki 19 @Anil_g  10 @NathanAlvares24  17 @VishnuReddy1997  6 @Expiscornovus  10 @Tjan  5 @Nived_Nambiar  10 @eetuRobo  3 @SudeepGhatakNZ 8     Week 3 Results: Congratulations to the Week 3 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 3:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji32ManishSolanki55VishnuReddy199724NathanAlvares2444Anil_g22SudeepGhatakNZ40eetuRobo18Nived_Nambiar28Tjan8David_MA22   Week 4 Results: Congratulations to the Week 4 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 4:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji11FLMike31Sayan11ManishSolanki16VishnuReddy199710creativeopinion14Akshansh-Sharma3SudeepGhatakNZ7claudiovc2CFernandes5 misc2Nived_Nambiar5 Usernametwice232rzaneti5 eetuRobo2   Anil_g2   SharonS2  

Check Out | 2024 Release Wave 2 Plans for Microsoft Dynamics 365 and Microsoft Power Platform

On July 16, 2024, we published the 2024 release wave 2 plans for Microsoft Dynamics 365 and Microsoft Power Platform. These plans are a compilation of the new capabilities planned to be released between October 2024 to March 2025. This release introduces a wealth of new features designed to enhance customer understanding and improve overall user experience, showcasing our dedication to driving digital transformation for our customers and partners.    The upcoming wave is centered around utilizing advanced AI and Microsoft Copilot technologies to enhance user productivity and streamline operations across diverse business applications. These enhancements include intelligent automation, AI-powered insights, and immersive user experiences that are designed to break down barriers between data, insights, and individuals. Watch a summary of the release highlights.    Discover the latest features that empower organizations to operate more efficiently and adaptively. From AI-driven sales insights and customer service enhancements to predictive analytics in supply chain management and autonomous financial processes, the new capabilities enable businesses to proactively address challenges and capitalize on opportunities.    

Updates to Transitions in the Power Platform Communities

We're embarking on a journey to enhance your experience by transitioning to a new community platform. Our team has been diligently working to create a fresh community site, leveraging the very Dynamics 365 and Power Platform tools our community advocates for.  We started this journey with transitioning Copilot Studio forums and blogs in June. The move marks the beginning of a new chapter, and we're eager for you to be a part of it. The rest of the Power Platform product sites will be moving over this summer.   Stay tuned for more updates as we get closer to the launch. We can't wait to welcome you to our new community space, designed with you in mind. Let's connect, learn, and grow together.   Here's to new beginnings and endless possibilities!   If you have any questions, observations or concerns throughout this process please go to https://aka.ms/PPCommSupport.   To stay up to date on the latest details of this migration and other important Community updates subscribe to our News and Announcements forums: Copilot Studio, Power Apps, Power Automate, Power Pages

Users online (1,262)