Exporting data from your website's database to a spreadsheet format is really very easy
Stunningly simple, but so often asked in newsgroups and messageboards. I've never posted this tutorial before, because it truly is a very simple trick.
A lot of ASP developers, especially newbies, don't realise that ASP is essentially format-neutral. Usually it's used to output HTML documents, sure, but it's capable of outputting virtually anything, and is especially good at outputting text-based formats such as XML and, key to this article, CSV.
If you can output a recordset to HTML, why not CSV? very simple
The algorithm, in plain english, is this :
Loop through each of the fields, outputting the field name followed by a comma.
End this line with a linebreak.
Loop through the recordset, outputting each value followed by a comma, ending
with a linebreak.
Write this lot to the browser.
Here's the code, outputting from a recordset of Formula OneTM drivers from the
2002 season.
function ADOToCSV() {
var objConn = new ActiveXObject("ADODB.Connection");
objConn.open(connectionstring);
var strSQL = "SELECT * FROM tblDrivers";
var objRS = objConn.execute(strSQL);
Response.ContentType = "application/octet-stream";
Response.AddHeader('content-disposition', 'attachment;filename=drivers.csv');
// output column names
for(var x=0;x<objRS.fields.count;x++) {
Response.Write(objRS.fields(x).name + (x<objRS.fields.count-1?', ':''));
}
Response.Write('\n');
while(!objRS.EOF) {
for(var x=0;x<objRS.fields.count;x++) {
Response.Write(objRS.fields(x).value + (x<objRS.fields.count-1?', ':''));
} Response.Write('\n'); objRS.moveNext();
}
}
Click Here to see this code in action
This code forces a 'save-as' dialog. If you don't want that, remove the content-disposition
line.