Here is the full code:
function createAndUploadFile()
{
var web = context.get_web(); //gets the web object
var list = web.get_lists(); //gets the list collection object
var targetList;
var fileCreation;
var fileContent;
targetList = list.getByTitle("Documents");
fileCreation = new SP.FileCreationInformation();
var d = new Date()
var utc = d.toJSON().slice(0, 10) + "-" + d.getHours() + "-" + d.getMinutes() + "-" + d.getSeconds();
var fileName = "EmployeeList" + utc; //gets the file name
fileName = fileName + ".xls";
fileCreation.set_url(fileName);
fileCreation.set_content(new SP.Base64EncodedByteArray());
fileContent = str;
//gets the file contents.
for (var content = 0; content < fileContent.length; content++) {
fileCreation.get_content().append(fileContent.charCodeAt(content)); //add the text content to the file.
}
//create a new file instance
var newFile = targetList.get_rootFolder().get_files().add(fileCreation);
context.load(newFile);
context.executeQueryAsync(onFileCreationSuccess, onFileCreationFail);
}
function onFileCreationSuccess()
{
alert("File created and uploaded in document library");
}
function onFileCreationFail()
{
alert("Error in creating file");
}
You can call this function on page load or wherever you want.
This worked for me and excel document got uploaded in document library without being downloaded.