Reorder the columns in SheetsJS

Using the xlsx library (based on SheetJS), I am able to generate an Excel file with specific column orders and custom headers. Here is how I create custom headers:

 const finalHeaders = [
      [
        this.tr.instant('shared.targetLanguage') as string,
        'No Items',
        this.tr.instant('reports.summarized.withoutimages') as string,
        this.tr.instant('reports.summarized.creativewrd') as string,
        this.tr.instant('reports.summarized.noncreativewrd') as string,
        this.tr.instant('shared.client') as string,
        this.tr.instant('shared.project') as string,
        this.tr.instant('shared.sourceLanguage') as string,
      ],
    ];

    /** Generate the excel file */
    const workBook = XLSX.utils.book_new();
    XLSX.utils.sheet_add_aoa(workBook, finalHeaders);

    const workSheet = XLSX.utils.sheet_add_json(workBook, data, { origin: 'A2', skipHeader: true });

    XLSX.utils.book_append_sheet(workBook, workSheet, 'Sheet 1'); // add the worksheet to the book
    XLSX.writeFile(workBook, `Quantitative_Summarized_Report_${new Date().toLocaleString()}.xlsx`);

After generating the Excel file, I need to sort the columns in a specific order without losing the custom headers. This can be achieved by sorting the columns while preserving the custom headers:

const sortedHeader = ['clientName', 'projectName', 'sourceLanguageName', 'targetLanguageName', 'numItems', 'numItemsWithoutImages', 'numWordsCreative', 'numWordsNonCreative'];

const workSheet = XLSX.utils.json_to_sheet(data, { header: finalHeaders });

Is there a way to combine these two solutions seamlessly? Thank you in advance.

Answer №1

At last, the task is complete! By utilizing a combination of two methods, I have successfully achieved it:


    const sortedHeader = ['clientName', 'projectName', 'sourceLanguageName', 'targetLanguageName', 'numItemsTarget', 'numItemsWithoutImages', 'numWordsCreative', 'numWordsNonCreative'];

    const finalHeaders = [
      [
        this.tr.instant('shared.client') as string,
        this.tr.instant('shared.project') as string,
        this.tr.instant('shared.sourceLanguage') as string,
        this.tr.instant('shared.targetLanguage') as string,
        'No Items',
        this.tr.instant('reports.summarized.withoutimages') as string,
        this.tr.instant('reports.summarized.creativewrd') as string,
        this.tr.instant('reports.summarized.noncreativewrd') as string,
      ],
    ];

    const workBook = XLSX.utils.book_new();
    
    XLSX.utils.sheet_add_aoa(workBook, finalHeaders);

    const workSheet = XLSX.utils.sheet_add_json(workBook, data, { origin: 'A2', header: sortedHeader, skipHeader: true });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for obtaining the accurate HTML code format using Angular 2's input feature:

I am looking to retrieve all the code with an input as [input] and a tag as #tag. When attempting to obtain HTML code with jQuery using console.log($("#content")[0].outerHTML);, this is an example of how the code looks: <div dnd-droppable [dropZones]= ...

Encountering a issue while running npm start with Angular 2 RC build

After upgrading from Angular2 beta 15 to the RC version, I encountered some errors while trying to run my application. typings/browser/ambient/es6-shim/index.d.ts(8,14): error TS2300: Duplicate identifier 'PropertyKey'. typings/browser/ambient/e ...

Using a jQuery plugin within an Angular 2 component: A step-by-step guide

Looking to implement an image slider plugin called Vegas only on the home page within my Angular 2 application. The Vegas jQuery plugin has been added via npm and is located under the /node_module directory. The following code snippet shows my home page c ...

Breaking down a Python array into individual characters for an Excel spreadsheet

After inputting the code into Excel, I noticed that every character is spaced out. This leads to "Tuesday" appearing as "T,u,e,s,d,a,y" in Excel. My objective is to have each cell in Excel display a complete word rather than individual characters. With n ...

Conceal the Button when the TextBox does not contain valid input

I'm trying to create a textbox with an email pattern that hides a span (click) if the pattern is invalid. I have the following code snippet in place, but it doesn't seem to work as expected: <input type="text" placeholder="Signup for Mailin ...

Create a blank PDF file by converting HTML to PDF using ItextSharp

I have been using Itexsharp.dll to convert HTML to PDF in a webapi and Angular 2 project. However, I am encountering an issue where the PDF generated is blank when I try to open it in Angular 2. Here is my code: Web API code: - HttpResponseMessage respon ...

The Angular interpolation feature does not function properly when attempting to use Font Awesome icons

The markup for the Angular Material Tree component examples can be found here: Angular Material tree with flat node example. <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding> <button mat-icon-button matTreeNodeToggl ...

Setting up Oauth2 OIDC in an Angular 8 application

I've been attempting to set up OAuth2 in my Angular project for user login. I followed the documentation, but whenever I try to log in, it keeps showing an Unauthorized error and I'm not sure how to resolve it. Here are my configurations: auth c ...

React-select initial value set to null after first selection

I've been working on a dropdown feature with the help of react-select: The options for the dropdown are fetched from an API endpoint, but I'm encountering a peculiar issue. When I initially select an option, my AccountSelected1 remains null. Sub ...

Encountering an error of TypeError while attempting to generate a new GraphQL

Currently using Apollo-Server/TypeScript with graphql-tool's makeExecutableSchema() to set up schema/directives. Encountering an error while attempting to add a basic GraphQL Directive: TypeError: Class constructor SchemaDirectiveVisitor cannot be in ...

How can a variable be used to assign a date value to an Angular Material datepicker?

Is there a way to modify the date of an item in an array? I've encountered an issue when attempting to input the selected object's date into the Material datepicker. Strangely, it seems to function properly if you manually type in a date as a str ...

Mastering the Application of useSelector with TypeScript

I am using the useSelector code snippet below: const user = useSelector<RootStateOrAny, typeof typeRootReducer>((state) => state.user) This is how it looks in the rootReducer: const rootReducer = combineReducers({ user: userReducer }) exp ...

The parent route guard in Angular triggers an infinite loop when navigating to a child route from the parent route

Imagine a scenario where we have a website containing profiles of various users, accessible only to authenticated users. I want the ability to enter an empty URL and then, upon authentication, be redirected to my profile. Additionally, I would like to dire ...

Issue encountered in Angular app-routing module.ts: Type error TS2322: The type '"enabled"' cannot be assigned to type 'InitialNavigation | undefined'

When I recently updated my project from Angular 11 to 14, I encountered the following error when running "ng serve". Error: src/app/app-routing.module.ts:107:7 - error TS2322: Type '"enabled"' is not assignable to type 'InitialNavigation | u ...

Error message occurs when the component containing a function child is used and results in: "Invalid JSX element, as the return type is not a valid ReactNode."

Check out this React code snippet: (codesandbox) import type { ReactNode } from 'react'; type RenderCallbackProps = { children: (o: { a: number }) => ReactNode, }; function RenderCallback({ children }: RenderCallbackProps) { return (chil ...

Can an L1 VPC (CfnVpc) be transformed into an L2 VPC (IVpc)?

Due to the significant limitations of the Vpc construct, our team had to make a switch in our code to utilize CfnVpc in order to avoid having to dismantle the VPC every time we add or remove subnets. This transition has brought about various challenges... ...

navigating through different pages on a react-native application

While building my app in react-native, I encountered some issues with setting up the navigation. I referred to the react-native documentation for guidance, specifically this navigation guide. The guide mentioned passing an object named "navigation" to your ...

I'm having issues with the functionality of my code inside the ng-template and ngIf. What could be

I am facing an issue with my method that is supposed to display the specified HTML content. However, it seems like the ngIf condition within the code block is not functioning correctly. Can someone help me understand why the ngIf statement is being ignored ...

What is the best way to choose a random text from a dropdown menu that contains several div elements using Playwright?

web element Is it possible to choose a "random" text using div tags from a dropdown? I am attempting to pick any random country from the dropdown with the following code in Playwright: const selectCountry = this.page.locator('<this locator>&apos ...

Is it possible to receive some leeway in terms of timing for the current moment?

I am currently working with the dayjs function and would like to make some adjustments to the "time now" functionality in order to prevent my test from failing if it takes longer than a minute to complete. Here is what I have at the moment; const dayjs = r ...