简体   繁体   中英

ExcelJS write an array to excel

I'm using an API where i fetch information and it stores in an array called res. I want this array to be written to an excel file. The first information in the array should be in A2 and the second in B2 etc etc.

This is my code:

const api2 = require("fordonsuppgifter-api-wrapper");



(async () => {
    console.log("fetching vehicle info");
    var res = await api2.GetVehicleInformation("XMP433");
    console.log(res);
})();


const Excel = require('exceljs');

const fileName = 'simple.xlsx';

const wb = new Excel.Workbook();
const ws = wb.addWorksheet('My Sheet');

const r3 = ws.getRow(3);
r3.values = [1, 2, 3, 4, 5, 6];

wb.xlsx
    .writeFile(fileName)
    .then(() => {
        console.log('file created');
    })
    .catch(err => {
        console.log(err.message);
    });

The API is working, but I can't get it to write to an excel file.

You can create excel file with both combination call. The exceljs library need to moving cell write function

ws.getCell(<cell_address>).value = <assigned_value>

cell_address needs to increase number for moving down(increase row number)

Example: A1 -> A2 for next row.

The columnName() can convert from integer to Excel Column Address.

Example

columnName(1) -> A
columnName(2) -> B

You needs to convert Object() from JSON to Object type Then can get the JSON key 's list

Object.keys(carData)

Final Code

const Excel = require('exceljs');
const api2 = require("fordonsuppgifter-api-wrapper");

const columnName = (index) => {
    var cname = String.fromCharCode(65 + ((index - 1) % 26));
    if (index > 26)
        cname = String.fromCharCode(64 + (index - 1) / 26) + cname;
    return cname;
}

const getCarInformation = async (keyword) => {
    try {
        const res = await api2.GetVehicleInformation(keyword);
        return Promise.resolve(res);
    } catch (error) {
        return Promise.reject(error);
    }
}

// Search car by keyword
getCarInformation("XMP433")
    .then((carData) => {
        const fileName = 'simple.xlsx';
        const workbook = new Excel.Workbook();
        // make workbook with 'car' name
        const ws = workbook.addWorksheet("car")

        // Start Cell A1 for title column
        let headerColumn = 1
        let section_number = 1
        for (let key in carData) {
            // title column, example : A1 = Sammanfattning
            ws.getCell(columnName(headerColumn) + String(section_number)).value = key
            subItems = carData[key]
            row_number = section_number
            for (let subKey in subItems) {
                // Sub title Cell Bx, example : B1 = Registreringsnummer
                ws.getCell(columnName(headerColumn + 1) + String(row_number)).value = subKey
                // value Cell Cx, example : C1 = '(2*) XMP433'
                ws.getCell(columnName(headerColumn + 2) + String(row_number)).value = subItems[subKey]
                row_number++;
            }
            // Jump to next title
            section_number = section_number + Object.keys(carData[key]).length;
        }
        workbook.xlsx
            .writeFile(fileName)
            .then(() => {
                console.log('file created');
            })
            .catch(err => {
                console.log(err.message);
            });
    })
    .catch(err => {
        console.log(err.message);
    });

Result in simple.xlsx

You need to click on header for expanding the width of a column to fit its contents after saved file.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM