I need to create HTML page with JavaScript which can store user information into excel directly. Information can contain user input fields like:
First Name (Datatype: Text)
Last Name (Data Type: Text)
I have tried below code for storing values into CSV but I don't know how to store value in excel sheet.
<hrml>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "D:\\sample.csv";
var file = fso.OpenTextFile(fileLoc, 8, true,0);
file.writeline(passForm.FirstName.value + ',' +
passForm.LastName.value);
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20">
Type your last name: <input type="text" name="LastName" size="20">
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
Kindly help me for this "How to write HTML input data into Excel using JavaScript"
Thank you so much in advance.
you can create an automation object (in windows) using ActiveXObject() in your javascript code. example:
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
// a text is stored in the first cell
ExcelSheet.ActiveSheet.Cells(1,1).Value = "Texto1";
// the sheet is saved
ExcelSheet.SaveAs("D:\\TEST.XLS");
// close Excel with the Quit() method of the Application object
ExcelSheet.Application.Quit();
You can generate a semicolon separated var with your data and use the window.open function, here is an example:
var data = '';
data += $('#Name').val() + ';'
data += $('#EmployeeID').val();
data += '\r\n';
window.open( "data:application/vnd.ms-excel;charset=utf-8," + encodeURIComponent(data));
You can also generate a formatted html instead a semicolon separated text.
This one uses ActiveX object to write to files on your PC.
It will work only on IE. This is forbidden in browsers by default.
Here's the "normal" use case and how you would be able to complete this with all browsers:
Get form's data (JavaScript)
Make an AJAX request to the server with the data (JavaScript)
The server should have some
logic to get the data and write it to a file (Excel file) (JavaScript, PHP, Java,
C#, 1000s more....)
If you want it to work everywhere, you should put some efforts to create some server too. You may start the server on your local machine so you'll have files saved locally
Related
Hi in an attempt to learn XML I have started a mini-project and am following this totorial: https://www.youtube.com/watch?v=ppzYGd0wi_c. However, the structure of my XML is a bit different to that of this video e.g. I have ids allocated to each section. I have pasted what my XML looks like below:
<?xml version="1.0" encoding=UTF=8?>
<peopleNetwork>
<person id="1">
<name>Alice</name>
<friend>Ruby</friend>
<image>images/ruby.jpg</image>
</person>
<person id="2">
<name>Tom</name>
<friend>Katty</friend>
<image>images/ketty.jpg</image>
</person>
</peopleNetwork>
Since I have id and the person in the video does not in his XML, would I need to process my data differently or would following the same structure work? Can someone point me to some resource / guide me how I can read and process a XML file that has data like above using JavaScript and HTML.
I have written the following code that prompts the user to select a file:
var input = $(document.createElement('input'));
input.attr("type", "file");
input.trigger('click');
return false;
But I am guessing there is more to it, for example saving the read data and processing it somehow. Whilst I have some experience in JavaScript but I have never came across reading and processing data files - therefore I am finding a really difficult - so any guidance on this would be nice.
I understand I will need to use Ajax as the person in the video is doing - one of my question is. In my data I have id however in the video the person doesn't, so I am not sure how to go about handling this.
I am a newbie in XML, but having watched the video I am guessing its something simple but I have no clue where to start. Any help would be appreciated.
Well you can still use input type='file' that allows you to select a file from the user's computer.Then we use FileReader.
html
<div>Xml File: <input type="file" id="fileInput" accept="text/xml" ></div>
<p id="MyXMLText"></p>
script: I'm using jquery and javascript here. This can also be achieved with pure js. We attach onchange event to the input and then use FileReader to open and read the xml as text.
$(function () {
$("#fileInput").on('change', function (e) {
var file = $("#fileInput")[0].files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (e) {
var fileContent = reader.result;
//Sorry cannot give you correct answer why xml parsing fails, but this has to be done here.
fileContent = fileContent.replace('<?xml version="1.0" encoding=UTF=8?>', '').replace(/(?:\r\n|\r|\n)/g, '');
var xmlDoc = $.parseXML(fileContent); //xml document is ready here
//Get all the details for person with id = 1
$("#MyXMLText").append($(xmlDoc).find('person[id="1"]').text() + '<br/>')
//Get the friend's details only for person with id = 1
$("#MyXMLText").append($(xmlDoc).find('person[id="1"]>friend').text() + '<br/>')
//Get the name details only for person with id = 2
$("#MyXMLText").append($(xmlDoc).find('person[id="2"]>name').text() + '<br/>')
}
});
});
parseXML
Let us know.
I developed a simple HTML5 form using Adobe LiveCycle ES4 + SP1 which will submit to Java JSP. Also, I developed simple JSP to retrieve the submitted XML from request InputStream.
What I am getting on the server is the concatenated values of the form fields. See snapshots below for more details.
Download XDP file: click here
Download JSP file: click here
The following lines of code are used to submit the HTML5 to the JSP which are placed under the click event of the "Save" button:
var theBtnSubmit = cmdSubmitForm.resolveNode("#event").submit;
var theTarget = form_config.server_url.rawValue + "?" + "action=save" + "&form_id=" + form_config.form_id.rawValue + "§ion_id=" + form_config.section_id.rawValue;
theBtnSubmit.target = theTarget;
cmdSubmitForm.execEvent("click");
The following lines of code are used to get the InputStream and convert to string:
ServletInputStream ris = request.getInputStream();
String theString = IOUtils.toString(ris);
The problem:
On the server, I am unable to retrieve the form fields and values in XML format. What I am getting is the concatenated values of the fields which are filled in the form.
Appreciate your help to solve this problem.
Actually, the above method is fine, the only thing is that I had to escape the XML output using the following lines of code:
<%#page import="org.apache.commons.lang3.StringEscapeUtils" %>
...
String theString = IOUtils.toString(ris, Charset.forName("UTF-8"));
theString = StringEscapeUtils.escapeXml10(theString);
out.print("input stream in string format : " + theString + "<br/>");
Please I need help to edit a txt file in client side, I can't find a good method. I need update the data automatic, without confirmation, like it:
<button onclick="updatefile()">Update</button>
<script>
functiom updatefile(){
var file = "d:\test.txt"
var data = //here any function for load all data from file
...
...
data .= " new data to add";
//here any function for save data in test.txt
.....
}
</script>
Please help me.
You cannot do this in that manner using JS. What you CAN do though is to download it on the client, without having the server intervene by using data urls.
Setting the name of said downloaded file is not cross browser compatible unfortunately...
HTML
<textarea id="text" placeholder="Type something here and click save"></textarea>
<br>
<a id="save" href="">Save</a>
Javascript
// This defines the data type of our data. application/octet-stream
// makes the browser download the data. Other properties can be added
// while separated by semicolons. After the coma (,) follows the data
var prefix = 'data:application/octet-stream;charset=utf-8;base64,';
$('#text').on('keyup', function(){
if($(this).val()){
// Set the URL by appending the base64 form of your text. Keep newlines in mind
$('#save').attr('href', prefix + btoa($(this).val().replace(/\n/g, '\r\n')));
// For browsers that support it, you can even set the filename of the
// generated 'download'
$('#save').attr('download', 'text.txt');
}else{
$('#save').removeAttr('href');
$('#save').removeAttr('download');
}
});
I apologize in the advance as I am a total beginner.
I have a pre-existing html form with text fields. I need to have a button that will allow me to upload a txt file (since when trying to look for answer about this, I learned javascript can't just access a file from my PC without me actively uploading it). Then I need the values from this txt file inserted into the text fields (for example, the form has: name, last name, phone etc - and the file will fill out this info).
I am going crazy trying to collect bits and pieces from other people's questions. any help would be greatly appreciated!
it depends on how you would like to have this handled, there are basically two options:
File Upload and page redirect
you could provide a file upload form to upload your textfile, redirect to the same page via form submission, handle the data on serverside (e.g. parse the file and get the values out of it) and let the server inject the values as default properties for the form file which is returned to the browser
XMLHttpRequest File Upload
in modern browsers, the native xhr object supports an upload property, so you could send the file via that upload property. it has to be sent to a serverside script that parses the file and returns the values in a fitting format, e.g. json (which would look like this: {'name':'somename', 'lastName':'someothername'}). then you have to register an eventlistener on completion of this upload (e.g. onload) and set these values on javascript side.
check this out for XMLHttpRequest upload (better solution in my opinion): https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
edit:
well, the easiest solution would be just to provide a textfield and paste the content of the file into this field, hit a button and the content is parsed. then you wouldn't rely on network traffic or even a serverside handling, but could do everything with javascript, e.g. like this:
dom:
<textarea id="tf"></textarea>
<button id="parse">fill form!</button>
js:
var tf = document.getElementById("tf");
document.getElementById("parse").addEventListener("click", function(){
var formData = JSON.parse(tf.value);
//if your textfile is in json format, the formData object now has all values
});
edit: from the link i posted in the comments:
<!-- The HTML -->
<input id="the-file" name="file" type="file">
<button id="sendfile">send</button>
and
document.getElementById('sendfile').addEventListener("click", function(){
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', '/upload/path', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var values = JSON.parse(xhr.responseText);
//these are your input elements you want to fill!
formNameInput.setAttribute('value', values.name);
formFirstNameInput.setAttribute('value', values.firstName);
}
}
xhr.send(formData);
});
as already said, your serverside has to parse the file and respond with json
So I've got my javascript array (var seatsArray = [];), let's say it has some contents. I want to write the contents of that array to a .txt file on the server when the user clicks a button. The text file will not already exist so it needs to be created.
Also, if anyone knows how I could allow the user to specify the name of the text file to be created by typing it in a text area, that would be great.
Any ideas?
Many thanks
John
EDIT:
Added the suggested code, however, nothing happens when I hit save?
<form id="my_form" action="">
<input type="text" id="file_name" rows="1" cols="20">
Save
</form>
<script type="text/javascript">
function submitform();
{
var d = seatsArray.join();
var url = "/txtfiles/"+d + "&file_name=" +
document.getElementById("file_name").value;
document.getElementById("my_form").action = url;
document.getElementById("my_form").method = "POST";
document.getElementById("my_form").submit();
}
</script>
That is all in the body section.
Thanks
You can layout a web form with, among other things, a text field for file name. Then write a Javascript submit event for the form and, in its handler, before send the data build the url with your data.
For the array you can join its data so its converted into a string with a comma separator
var seatsArray = [1,4,5,6];
var d = seatsArray.join(); // "1,4,5,6"
var url = "http://my_site/my_file.php?my_array="+d + "&file_name=" +
document.getElementById("file_name").value;
document.getElementById("my_form").action = url;
document.getElementById("my_form").method = "POST";
document.getElementById("my_form").submit();