0

I am uploading an Excel file and inserting into a mysql table. My code is working with Linux. But I want it should run with other also so I am predicting that Xls is not working.

How to change into CSV or any other way so we can upload the Excel or csv which support any version?

function getfileDetails(req, res) {
    var sampleFile, fileInfo = {};
        var date1=new Date();
         var currdatetime = date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate()+" "+date1.getHours()+":"+date1.getMinutes()+":"+date1.getSeconds();
        console.log(currdatetime);
    var MyData = [];
            if (!req.files) {
            res.send('No files were uploaded.');
            return;
          }   
          sampleFile = req.files.fileInputXLSX1;

        var datetimestamp = Date.now();

          console.log("Uploaded -- ",sampleFile);
          var fileExtn = sampleFile.name.split(".").pop();
          var extractedFilename = sampleFile.name.slice(0, sampleFile.name.lastIndexOf('.'));
          var userid=req.headers['userid'];
          var uploadFileName = extractedFilename+'_'+userid+'_'+datetimestamp+'.'+fileExtn;

          console.log("uploadFileName -- ",uploadFileName);
          fileInfo = {
            "name": uploadFileName,
            "mimetype": sampleFile.mimetype
          }
          // Use the mv() method to place the file somewhere on your server  
          sampleFile.mv(__dirname+'/Details/'+uploadFileName, function(err) {
            if (err) {
                res.status(500).send(err);
                }
                var parseXlsx = require('excel');
                parseXlsx(__dirname+'/Details/'+uploadFileName, function(err, data) {
                    if(err) throw err;          
                    // data is an array of arrays
                    else{
                        if(data!=null)
                    {
                        var queryString= "Truncate table `details`;"
                        connection.query(queryString, function(err,result){
                                        if(err) { 
                                            res.write(JSON.stringify(err));
                                                res.end();
                                                } else {
                                                    res.send('File uploaded!');
                                                        }
                                                });
                    }
                            for (var index = 1; index < data.length; index++) 
                            {
                                MyData.push(data[index][0],data[index][1],data[index][2],data[index][3], data[index][4], data[index][5],data[index][6],data[index][7],data[index][8],data[index][9]);
                                var queryString="INSERT INTO `details`(name,tname,fname,timestamp) VALUES ('"+data[index][0]+"','"+data[index][1]+"','"+data[index][2]+"','"+currdatetime+"')";
                                    connection.query(queryString, function(err,result){
                                        if(err) { 
                                            res.write(JSON.stringify(err));
                                                res.end();
                                                } else {
                                                    res.send('File uploaded!');
                                                        }
                                                });
                            }   

                        }
                });         
         if(err) {
           res.status(500);
            res.send(err);
               }
        });

}

Please help ,I am New in Node.

2 Answers 2

1

hey can you try json2csv npm module. this will solve you problem @TB.M

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

Comments

0

This code is working fine, try this..

var xlsx = require('node-xlsx');
    var fs = require('fs');
    var obj = xlsx.parse(__dirname + '/new.xls'); // parses a file
    var rows = [];
    var writeStr = "";

    //looping through all datarow
    for(var i = 0; i < obj.length; i++)
    {
        var dataRow = obj[i];
        //loop through all rows in the sheet
        for(var j = 0; j < dataRow['data'].length; j++)
        {
                //add the row to the rows array
                rows.push(dataRow['data'][j]);
        }
    }

    //creates the csv string to write it to a file
    for(var i = 0; i < rows.length; i++)
    {
        writeStr = writeStr + rows[i].join(",") + "\n";
    }

    //writes to a file, but you will presumably send the csv as a      
    //response instead
    fs.writeFile(__dirname + "/data.csv", writeStr, function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("data.csv was saved in the current directory!");
    });

6 Comments

install node-xlsx with npm npm install node-xlsx Then use it with your excel file.
i m trying but in mycode its not giving proper output..can u come on chat?
No right now I am busy please don't mind, we can talk after 5 hours.
Check it doesn't handle commas in the values, you'll need to add double quotes and escape values containing double-quotes
In questions i have given my code.In that i need to add yours. how i should add given code.That is not happening.
|

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.