What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file?

To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunker:

https://stackblitz.com/edit/angular6-export-xlsx?file=src%2Fapp%2Fservices%2Fexcel.service.ts

The provided example successfully handles hard-coded JSON data. However, in my scenario, the backend sends data like:

0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAOwADAP7/CQAG.....

This backend data is compatible with another Java application for writing into Excel.

public exportAsExcelFile(json: any[], excelFileName: string): void {
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    console.log('worksheet',worksheet);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet },
                                      SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 
'array' });
    
    this.saveAsExcelFile(excelBuffer, excelFileName);
}

private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {
        type: EXCEL_TYPE
    });
    FileSaver.saveAs(data, fileName + EXCEL_EXTENSION);
}

The method XLSX.utils.json_to_sheet(json); has been utilized to convert JSON to Excel format, but my incoming data isn't in JSON structure.

An error message occurs stating:

ERROR TypeError: js.forEach is not a function
at sheet_add_json (xlsx.js:20696)
at Object.json_to_sheet (xlsx.js:20724)

This error specifically points to the line:

const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);

If anyone could recommend a suitable alternative code snippet to replace

XLSX.utils.json_to_sheet(json)

Answer №1

If you find yourself dealing with unstructured data that is not in JSON format and you need to transfer it to an Excel file, the process can be quite tedious as you have to manually input each cell using the specific Excel Library you are working with. For instance, when using XLSX, you can achieve this by :

XLSX.utils.sheet_add_aoa(worksheet, [["brand new information", 5, 6, 7]], {origin: -1});

This code snippet will add a new row at the bottom of the Excel sheet with the specified data ['brand new information', 5, 6, 7].

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

How to Delete an Item from an Array in BehaviorSubject Using Angular/Typescript

I have encountered an issue while trying to delete a specific element from my array upon user click. Instead of removing the intended item only, it deletes all elements in the array. I attempted to use splice method on the dataService object, but I'm ...

Trigger @HostListener event after a certain delay

I am currently working on implementing a basic infinite-scroll directive in Angular2. To achieve this, I am utilizing @HostListener('window:scroll') to capture the scroll event and extract the data from the $target. My concern is that every time ...

Having trouble with importing rxjs operators

After updating the imports for rxjs operators in my project to follow the new recommended syntax, I encountered an issue with the "do" operator. While switchMap and debounceTime were updated successfully like this: import { switchMap, debounceTime } ...

Leveraging the @Input decorator to send external data into the Angular component

In my Ionic app, I am utilizing an Angular component. Within this component, there is a variable called headerText that is supposed to be initialized from the page where the component is being used. The issue arises when the headerText variable is always ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

What is the process for generating an object type that encompasses all the keys from an array type?

In my coding journey, I am exploring the creation of a versatile class that can define and handle CRUD operations for various resources. The ultimate goal is to have a single generic class instance that can be utilized to generate services, reducer slices, ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

Unlock the Power of Typescript: Using the Browser Console to Access Functions

Scenario Within the file ts/app.ts, the following function exists: function foo() { console.log('Hello Word'); } After successful compilation with Webpack, it generates a file named bundle.js. To load this file, use the following script tag ...

Unlock the Power of Angular: Leveraging ViewEncapsulation.Native to Access HTML Elements

I am encountering an issue where I am receiving an error when trying to access an HTML element by ID. The problem arises when I attempt to access the classList upon a user clicking a button to apply a different style class to the element. The class list an ...

Transferring information between components is made easy with ng-content

In my application, I have a set of components that are used to create cards: <app-card-container> <app-card-title>Card title</app-card-title> <app-card-body> // some content </app-card-body> </app-card-con ...

Typescript: Firebase App type does not include delete, installations, name, or options properties

Exploring the realm of Typescript and its compatibility with Firebase has been a recent endeavor of mine. I've created a FirebaseProvider that requires a Firebase app to be configured in the following manner: import firebase from "firebase/app&qu ...

How to access a static TypeScript variable in Node.js across different files

I encountered a situation like this while working on a node.js project: code-example.ts export class CodeExample { private static example: string = 'hello'; public static initialize() { CodeExample.example = 'modified'; } ...

The Angular component refuses to open

Having some trouble with my navbar containing different components that should open upon selection. The profile component is opening correctly, but the "My favorites" button isn't displaying anything from that component. Here's the code snippet ...

Creating a Typescript interface where one property is dependent on another property

Let's look at an illustration: type Colors = { light: 'EC3333' | 'E91515' dark: '#100F0F' | '140F0F' } interface Palette { colorType: keyof Colors color: Colors[keyof Colors] } Is it possible for the ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

Exploring Sequelize: Uncovering the Secret to Retrieving Multiple Associated Items of Identical Type

Within my database, I have a situation where there are two tables sharing relations of the same type. These tables are named UserCollection and ImagenProcess UserCollection has two instances that relate to ImagenProcess. Although the IDs appear unique whe ...

Typedoc does not create documentation for modules that are imported

Whenever I generate documentation with TypeDoc, I am encountering an issue where imported files come up empty. If I add a class to the file specified in entryPoints, I get documentation for that specific class. However, the imported files show no document ...

Tips for integrating CKEditor into an Angular 4 project

To start using CKEditor, I first installed it by running the command npm install ng2-ckeditor. Next, I included ckeditor.js in my index.html file. I then imported { CKEditorModule } from 'ng2-ckeditor'; in my app.module.ts file. After setup, I ...

Is it advisable to flag non-(null|undefined)able type arguments as a type error?

Can the function throwIfMissing be modified to only flag test1 as a compiler error? function throwIfMissing<T>(x: T): T { if (x === null || x === undefined) { throw new Error('Throwing because a variable was null or undefined') ...

Challenges encountered when sending an HTTP post request in Ionic 2 with Angular 2

Whenever I try to make a post request in my ionic2 application, I encounter an error without any specific message. It seems like there is something wrong with my Angular2 post request. Below is the function I am using for the request: load(username, pass ...