Javascript Download to excel sheet - javascript

There is an HTML table as
<table>
<tr><th>NAME</th></tr>
<tr><td>SAL</td></tr>
<tr><td>TOM</td></tr>
<tr><td>SAM</td></tr>
<tr><td>Jenny</td></tr>
</table>
Download to excel sheet
On click hyperlink how to save the table to excel sheet

You might want to try using the XLSX.js lib http://blog.innovatejs.com/?tag=xlsx-js
There is an example there on how to export to excel which gives examples.
Note this exports to the XLSX format not XLS. But this should not be a problem for most use. The source is on GitHub: https://github.com/stephen-hardy/xlsx.js

You may want to take a look at table2CSV, since Excel can open csv files with no problem (and as a bonus other software can do it too, like OpenOffice). If you need it to be cross-browser, there's no way of generating a downloadable file, for that you need a server side script like the one in the example in the page I linked.

I have developed a product called scriptscraper which is designed to solve that problem.
Get the trial installed because the demonstration projects download data from yahoo finance and store the data in Excel. For that simple html table it would be no problem to do what you need.

Try this:
function makeSheet() {
var x = theTable.rows
var xls = new ActiveXObject("Excel.Application")
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++){
var y = x[i].cells
for (j = 0; j < y.length; j++){
xls.Cells( i+1, j+1).Value = y[j].innerText
}
}
}

Related

Can I extract a formatted string from a PDF File name in JavaScript?

I have seen some questions regarding extracting information from a PDF file using JS.
I am wondering if there would be anyway to build a program where I can drag upload a file ( or group of files ) into a GUI and then convert the PDF file names into a table of strings... but formatted.
I have a bunch of PDF formatted like
“First.Last.Date”
My job requires me to go through a long list of PDF files, manually read the names within, and then search for them in a database, and if I could do this in a JavaScript program then my workflow time would be cut in half ( if not more ).
Sorry if this question lacks any code. I am not sure if this is worth perusing in JavaScript and not sure where to start with file uploads.
I'm not exactly clear on what you want to do with the file names once you've got them, but the following code will get you the file names.
document.getElementById('myfiles').onchange = function (e) {
var fileList = [];
for (var i = 0; i < e.target.files.length; i++) {
fileList.push(e.target.files[i].name);
}
console.log(fileList);
};
<label for="myfile">Select PDF file(s):</label>
<input type="file" id="myfiles" name="myfiles" multiple>

Writing to Excel spreadsheet with ASP.Net site using the Excel Javascript API

I have created an ASP.Net webapp using the Empty Template in Visual Studio 2017. The website has many familiar Web Controls such as Button (s), ImageButton, and Label (s). Users open a picture inside the ImageButton control and are able to click inside the control. The webapp calculates a value depending on where the user clicks in the ImageButton, and the values are displayed in the corresponding Label controls. The user is meant to write the values into an open Excel Spreadsheet (this is where the issue lies). For additional context, every action taken by the user is handled by a client-side javascript function-- with the exception of opening the picture. The opening action is handled by C# code belonging to the aspx page.
In the process of writing a similar Excel Web Add In, I found some very helpful code for writing to an Excel Spreadsheet using the Excel JavaScript API.
Here is that very code:
function HighlightCell() {
Excel.run(function (ctx) {
// Create a proxy object for the selected range and load its properties
var sourceRange = ctx.workbook.getSelectedRange().load("values, rowCount, columnCount");
var sheet = ctx.workbook.worksheets.getActiveWorksheet()
// Run the queued-up command, and return a promise to indicate task completion
return ctx.sync()
.then(function () {
var highestRow = 0;
var highestCol = 0;
var highestValue = sourceRange.values[0][0];
// Find the cell to highlight
for (var i = 0; i < sourceRange.rowCount; i++) {
for (var j = 0; j < sourceRange.columnCount; j++) {
if (!isNaN(sourceRange.values[i][j]) && sourceRange.values[i][j] > highestValue) {
highestRow = i;
highestCol = j;
highestValue = sourceRange.values[i][j];
}
}
}
cellToHighlight = sourceRange.getCell(highestRow, highestCol);
cellToHighlight.format.fill.color = "IndianRed";
cellToHighlight.values = 5;
})
.then(ctx.sync);
})
.catch(errorHandler);
}
The code works like a charm within the Excel Web Add In, but it hasn't worked so far within the ASP.Net webapp. From my understanding, it is because the code hasn't been able to retrieve the active workbook / worksheet. This could be because of the disconnect between the server and the client-side from what I know.
Is there any way to open an excel spreadsheet on the client-side with javascript or C#. Can I even use the above code in an ASP.Net webapp?
EDIT: more code
I opened the spreadsheet on the client side with this code:
function excload() {
var selectedFile = document.getElementById('imgupload').files[0];
document.getElementById("frame").src = window.URL.createObjectURL(selectedFile);
}
In this code, imgupload is an HTML file input and "frame" is an iframe element. I'm not sure why when I run it, instead of just opening the spreadsheet in the iframe, it opens the spreadsheet in a new instance of the Excel program on the computer.
Noticed something weird in writing code:
Calling the function HighlightCell--which writes to the cell refreshes the page, while none of the other javascript functions do. This happens even if I add a return false; line to the function and call it from button with _onclick ="HighlightCell(); return false;"
REDUX of "Noticed something weird in writing code":
Managed to call Highlight cell without refresh by using:
$(document).ready(function () {
$('#chosen').click(HighlightCell);
});
But still no writing takes place

Read data from excel to database in sailsjs

Recently, I try to learn sails.js. Thus I learn it through google and internet, and sails.js is still new, I encountered some trouble while finding any example of reading data from excel (*.xls and *.xlsx files). Can anyone show me how? On google, I found xlsx module (install by npm install xlsx ) but I still dont know what I have to write in controller and in view files. Thank you a lot!
xlsx will permit you to read a file at the server level, but you're going to have to work on the code to get that data into your views. I can't tell if you're trying to upload files and then read them or just read a static file. At any rate I hope that this is a start as it surely isn't a comprehensive solution.
Here is some example code from one of my scripts that goes down the rows and gets some info from some cells.
var XLSX = require('xlsx'),
xls_utils = XLSX.utils;
var workbook = XLSX.readFile('./file.xls');
var num_rows = xls_utils.decode_range(sheet['!ref']).e.r;
var sheet = workbook.Sheets[workbook.SheetNames[0]];
for(var i = 0, l = num_rows; i < l; i++){
// Get cell in {c}olumn 2 (0=1 like arrays) and {r}ow: i
var cell = xls_utils.encode_cell({c:1, r:i});
var value = sheet[cell];
// Do something with value here
}
You can do a lot more with it and you'll have to play around with it. I find the documentation to be a little rough to get through but the info is all there.

List Google Drive files from a given folder on a webpage

I'm looking for a way to list all files in specific google drive folder, also which updates the list automatically, and let everyone possible to look. I've found quite amount of articles that creates a spreadsheet to list them but they don't update themselves. I just can understand bit of JavaScript of I tried to modify some of other codes to no avail. Here is what I've done.
I created a Google Apps Script file
function doGet(e){
return HtmlService.createHtmlOutputFromFile('list.html');}
and inside list.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var dir = "SpinFest2016 KPDS Clips"
function listFilesInFolder(dir) {
var folder = DriveApp.getFoldersByName(dir).next();
var contents = folder.getFiles();
var file;
var name = [];
var date = [];
var desc = [];
for (var i = 0; i < contents.length; i++) {
file = contents[i];
name[i] = file.getName();
date[i] = file.getDateCreated();
desc[i] = file.getDescription();
};
};
</script>
</head>
<table style ="width: 100%">
<tr>
<th>이름</th>
<th>제출일</th>
<th>비고</th>
<tr>
<td><p id="name"></p></td>
<td><p id="date"></p></td>
<td><p id="desc"></p></td>
</tr>
<script type="text/javascript">
document.getElementById("name").innerHTML = name;
</script>
</table>
</body>
</html>
I tried to list only file names first but it never worked, and I can't figure out what's wrong. If you can point me which part is wrong and what I have to do, I'd very appreciate you're help. If there's any other better way (not only google-apps-script but also other ways to display file list) that fits conditions below I'd very thankful.
lists file names in google drive
anyone with link can view the list
list updates automatically (whether periodically or on any change occurs)
getFiles() will return a FileIterator, it may not have a .length property. Change the loop into a while-loop and check if the iterator hasNext is true, this way it will iterate. Also, try to change how you push items in to the array. See the modified snippet, hopefully this works.
while (contents.hasNext()){
file = contents.next();
name.push(file.getName());
date.push(file.getDateCreated());
desc.push(file.getDescription());
};
What goes after this, how you display it will be up to you.
As written, your doGet gives a web browser an HTML page with some JS code embedded in it, which the browser will try to execute. And fail, since a web browser has no idea about DriveApp; it can run JavaScript, not Apps Script.
It's possible to execute Apps Script code in scriplets embedded in a page served by doGet, but the syntax make take a while to get used to.
For a simple page like yours, I would just create all HTML within doGet function, and serve that. See my example.
There was one more issue with your code: folder.getFiles() returns a file iterator, not an array. This is something you loop over using hasNext and next methods, as shown below.
function doGet(e) {
var template = '<table style ="width: 100%"><tr><th>name</th><th>Date</th><th>Description</th></tr>APPS_SCRIPT_CONTENT</table>';
var dir = 'SpinFest2016 KPDS Clips';
var folder = DriveApp.getFoldersByName(dir).next();
var contents = folder.getFiles();
var file, name, date, desc, list = [];
while (contents.hasNext()) {
file = contents.next();
name = file.getName();
date = file.getDateCreated();
desc = file.getDescription();
list.push('<tr><td>' + name + '</td><td>' + date + '</td><td>' + desc + '</td></tr>');
}
var output = HtmlService.createHtmlOutput(template.replace('APPS_SCRIPT_CONTENT', list.join('')));
return output.setTitle('Directory List').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
This will serve up a static HTML file with the current snapshot of the directory. If the user reloads, they will get a possibly fresher copy. The file will not update on its own if the directory contents are changed; I don't think this even possible on this platform. With a scriplet running Apps Script code, one could try to update periodically, but this seems hardly practical: why waste your Apps Script execution time quota on users who opened your webpage and went for a walk?

Export XML to Excel spreadsheet using Javascript/classic-ASP

I'm trying to export XML data from a web page to a spreadsheet using javascript. So far I've just tried the very simple:
Sub Export
Response.ContentType = "application/vnd.ms-excel"
<script>
var XML = document.getElementById("xmldata");
window.open(XML);
</script>
End Sub
This tries to open the XML file as an excel spreadsheet, however it doesn't open because it has invalid characters. I've tracked down these characters and the main culprit tends to be the horizontal dash "–". There may be other invalid characters, but If I remove them manually, the XML file opens fine.
How would I go about formatting the XML content to remove or replace the invalid characters to display properly to excel? The XML sheet is built from fields in a database, should I format it as it's built or format it with javascript? I'm trying to find the simplest solution possible as I'm fairly new to web programming. Also, I'm using classic ASP/VBscript.
Managed to solve it by getting the HTML table output from the XML data then putting that into Excel using ActiveX.
var x=listingTable.rows
var xls = new ActiveXObject("Excel.Application")
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++)
{
var y = x[i].cells
for (j = 0; j < y.length; j++)
{
xls.Cells( i+1, j+1).Value = y[j].innerTex
}
}
You have a mismatch in character encoding. Likely the client is assuming UTF-8 character encoding but you are sending from the server an ANSI encoding such as Windows-1252.
You need to ensure that the client knows that the server is sending Windows-1252 using Response.CharSet = "Windows-1252" in you server side code and including the following at the start of your xml:-
<?xml version="1.0" encoding="Windows-1252" ?>
Alternatively if you are using Response.Write to send the XML content you could use:-
Response.Codepage = 65001
Response.CharSet ="UTF-8"

Categories

Resources