How to save/import data from excel into database with NodeJS?

Viewed 37

i have a problem that how can i save data in excel file into the database. I have created the model in order to save data

Here is my model:

import Sequelize from 'sequelize';
import { sequelize } from '../config/database-config.js';

export const City = sequelize.define("city", {
    city_id: {
      type: Sequelize.INTEGER,
      primaryKey: true, 
      autoIncrement:true,
    },
    name: {
      type: Sequelize.STRING,
      unique: true,
      required:  [true, 'City name required'],
    },
    city_rank: {
      type: Sequelize.STRING,
      unique: true,
      required: [true, 'City rank required'],
    },
  }, { sequelize, freezeTableName: true}
)

export default City;

Routes

router.get("/saveExcel", exportCity);

For now, i need help to create controller and i hope anybody can help me. Some ideas would be great.

1 Answers
  1. Install xlsx npm module.

    npm install xlsx

2.Import the xlsx module and below code snip

var XLSX = require('xlsx')
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
console.log(xlData);

Now, you get the data in JSON form. you are using sequelize so using bulkCreate() method you can insert all records of excel into the database.

Related