How do I convert an html table to an Excel File? - html

I'm trying to get my page Data.aspx to return an html table, but I want that table to be in an excel format. This is my code so far.
In the Data.aspx Load:
Response.Clear()
Select Case lstrCmd
Case "summary"
Response.Write(Summary())
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Case "export"
Response.ContentType = "application/ms-excel"
Response.AddHeader("Content-Disposition", "attachment;filename=" & _
mstrProjectName & ".xls")
Response.Write(SummaryExport())
End Select
Response.End()
So the add header is where I'm puzzled. This is something another peice of my software uses, but I'm not sure if it will work..
the jquery that calls this is using ajax:
function btnSubmitExport_Click() {
var compID = $("#ddlCompanies").val();
var projectID = $("#ddlProjects").val();
var startDate = $("#txtStartDate").val();
var endDate = $("#txtEndDate").val();
var compName = $("#ddlCompanies :selected").text();
var projectName = $("#ddlProjects :selected").text();
$("#content").html("<div class='loading'>loading...</div>");
$.ajax({
url: "Data.aspx",
data: {
CompanyID: compID,
ProjectID: projectID,
CompanyName: compName,
ProjectName: projectName,
StartDate: startDate,
EndDate: endDate,
Cmd: "export"
},
success: function(html) {
$("#content").html(html);
},
error: function(response) {
alert(response);
}
});
}
So, typically, when I request this data, I just throw the resulting html into a "content" div on my default.aspx page.. but I want that html to be an excel file!
Any hints or thoughts on this would be helpful.
I see the same question in other places, but not any answers that help me with my existing code..

If you have an html text contains Table tag in it, simple save it with extension of XLS and Microsoft Excel will open it like a charm! And also as I've seen, you want user to download the file, not to show its content in the page. You should redirect page on your ASPX page directly (without using JQuery). I'd suggest you to use network monitor in the developer tools to see what's happening.
Cheers

Normaly you would need to use this header
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "filename=excelfile.xls"
Print all the output as you want it in this specific page and that would be it.
Research on these headers and you will be fine.

Related

Can i send data from one website’s console to another?

So im trying to automate a task at work, and im wondering if theres anyway to send data from the console of one webpage to the console of another web page.
The task i am trying to automate consists of a website that has a prefilled form. I need to get elements from this form, and then copy them into another totally different website. Ive already written a script that pulls the data i need from the form and displays it in the console. Now I need to find a way to send the data (which is simply variables) to the other page’s console. Is this possible?
Keep in mind this is in a work computer, not allowed to download anything on it.
Are you an admin of the webpages and are these pages from the same site? if the answer is yes, i would recommend you use localStorage for saving and retrieving the data then display it to the console.
If it's not your website and you want it to work anyway just create a simple browser extension.
Here are some links to help you get started with extensions
MDN doc
Chrome doc
The idea is for you to target webpage A collect the data and post it to Github
Then target webpage B to read data from your github gist and you dispaly it in the console.
Cheers, i hope it was helpfull
Which server side language are you using ?
Usually for these, you could just have a form which is posting data to another website's form.
Look at this php example :
https://www.ostraining.com/blog/coding/retrieve-html-form-data-with-php/
Correct me If I did not understand your question correctly.
//Store the logs in following way
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
//copying the logs into a json file
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
console.save(console.logs) //prints the logs in console.json file
// from the console.json file, you can use log information from another page
//Store the logs in following way
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
localStorage.setItem('Logs', console.logs);
localStorage.getItem('Logs'); // from any browser

get html code from a div

Im getting the html code from div with html() like this :
var s = $("#content").html();
and sending them to create a new page with this content with ajax :
$.ajax({
method: "POST",
url: "create.jsp",
data: {PageContent: s,
AppName: name,
header : temp
},
dataType: "html"
});
and this is how I create it with java :
File strFile = new File(strPath);
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
objWriter.write(header);
objWriter.write(content);
objWriter.write(" </div>");
objWriter.write(" </body>");
objWriter.write("</html>");
objWriter.flush();
objWriter.close();
Everything is good except when I open the new file I found all the html code in one line ! anyone knows a solution?
Update
it seems that the html() method is extracting the code in one line as i tested ! so is there any solution?

Export d3-generated HTML table as CSV (must work on IE too)

From JavaScript, I make an ajax/xhr d3.csv() call which triggers a lengthy MySQL query (which can sometimes take more than 30 seconds to run). An HTML table is then generated (via d3.js) from the data.
I want the user to be able to download the data as a CSV file via a button click, but
I don't want to create a tmp file on the server for this
Running the query again on the server is not an option -- I don't want to make the user wait another 30 seconds (nor tie up the database again)
I want to specify the filename, e.g., descriptiveName-some_datetime_here.csv
It needs to work in IE (corporate America thing) and Safari (corporate Executive thing)
Converting the JSON data that d3 created into CSV is not an issue (I know how to do that part).
There are many similar SO questions, and the general consensus seems to be: use a data URI and specify the filename in a download attribute (Q1, Q2, etc.).
But that attribute is sadly not supported on IE or Safari.
Maybe there is a better way, but here's one way to do it: submit a form with the desired filename and the data as two hidden form elements. Have the server simply return the data with the appropriate headers set for a file download. No need for tmp files; works on all browsers.
HTML:
<form id="download-form" method="post">
<input type="button" value="download CSV">
</form>
<!-- the button is right above the HTML table -->
<table>... </table>
JavaScript/D3:
var jsonData;
var filenameDateFormat = d3.time.format("%Y%m%d-%H%M%S");
// ... after loading the data, and setting jsonData to the data returned from d3.csv()
jsonData = data;
// display the form/button, which is initially hidden
d3.select("#download-form").style("display", "block");
d3.select("#download-form input[type=button]").on('click', function() {
var downloadForm = d3.select("#download-form");
// remove any existing hidden fields, because maybe the data changed
downloadForm.selectAll("input[type=hidden]").remove();
downloadForm
.each(function() {
d3.select(this).append("input")
.attr({ type: "hidden",
name: "filename",
value: CHART_NAME + "-"
+ filenameDateFormat(new Date()) + ".csv"});
d3.select(this).append("input")
.attr({ type: "hidden",
name: "data",
value: convertToCsv(jsonData) });
});
document.getElementById("download-form").submit();
});
function convertToCsv(data) {
var csvArray = ['field_name1_here,field_name2_here,...'];
data.forEach(function(d) {
csvArray.push(d.field_name1_here + ',' + d.field_name2_here + ...);
});
return csvArray.join("\n");
}
Server (Python, using Bottle):
#app.route('/download', method='POST')
def download():
if request.environ.get('HTTP_USER_AGENT').find('Chrome'):
# don't add the Content-Type, as this causes Chrome to output the following
# to the console:
# Resource interpreted as Document but transferred with MIME type text/csv
pass
else:
response.set_header('Content-Type', 'text/csv')
response.set_header('Content-Disposition',
'attachment; filename="' + request.forms.filename + '"')
return request.forms.data
Not pretty, but it works.

How to pass data back to webpage?

I am working on a WP8 application, containing the WebBrowser control in which I open a html page, containing javascript. The javascript contains the following function:
function send(data) {
windows.external.notify(data);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'getresponse', false);
xhr.send(null);
var result = xhr.responseText;
if (result) {
return JSON.parse(result);
}
}
Basically this function calls the native C# side of the app, where I run some functions and I need to be able to return some data from the native side to the send function. I wanted to use an XMLHttpRequest for this, where my idea was to "intercept" the request url (in this case 'getresponse') and return the data I want by including it in the response.
Is this please possible on Windows Phone 8 using the WebBrowser control?
Once again, all I need to do is this:
Have a javascript function (in this case called "send") which connects to the native app (using windows.external.notify) and pass data back to this "send" function so that it can return it (and so that other JS function can use it).
Is this please possible? If not using the XMLHttpRequest, maybe using another technique?
Thank you all for your help!
You are looking for InvokeScript.
If you have full control over the page that is displayed inside the WebBrowser (e.g. the server is your's), you can define the JS-function to be called:
webBrowser.InvokeScript("yourJSFunction", "param1", "param2");
If you display a website from a foreign webserver you can inject JS like this (this uses jQuery):
webBrowser.InvokeScript("eval", "window.youInjectedFunction = function() {" +
"window.external.notify('and_notify_back');" +
"}; " +
"window.readyStateCheckInterval = setInterval(function() {" +
"window.external.notify('timer');" +
"if (document.readyState === 'complete') {" +
"clearInterval(window.readyStateCheckInterval);window.yourInjectedFuntion();" +
"}}, 100);" +
"");
I used the timer, as you can not be certain if the InvokeScript is called after the page is completely loaded.
If you can control the source, you should definitely go for option 1.

Writing HTML into a new tab

In my extension, I'm creating a new tab and would like to write my own html to it - that's generated dynamically.
Can it be done.
I'm calling chrome.tabs.create() to create a new tab - now I just need to write my data as an HTML file to it.
Easiest way to do this would be using a data: URL. E.g. something like this:
var htmlCode = "<html><body>Hi!</body></html>";
var url = "data:text/html," + encodeURIComponent(htmlCode);
chrome.tabs.create({url: url});