-1

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.

3
  • Your question is unclear. Why doesn't your save work? Commented Sep 7, 2022 at 10:44
  • Basically, for example you have a bunch of excel file, now the problem is i have an issue that my project want me to import excel file to database and i do not know how to do it. Commented Sep 7, 2022 at 10:54
  • So the problem is that you don't know how to read an excel file, not how to save it. Start with googling "how to send a file to the backend nodejs". Then you will need to read the file - "nodejs read xlsx" Commented Sep 7, 2022 at 10:56

1 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

4 Comments

Could you add some more, i need more information
Kato, can you please share which information you need?
Whole controller to import data from excel
you are getting excel data in xlData variable so you need just fire a query to insert those data if the excel header's name and your database entity attribute name is varied then only you need to manipulate the JSON object and then fire the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.