How to export an HTML table to a CSV file in JavaScript - Project Video

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys here going in this video I'm going to show you how to export an HTML table to a CSV file using plain JavaScript so this here's the final result we have an HTML table if I press on the export to saves CSV button it's going to download automatically a CSV file containing the tables contents and I can open in any csv viewer and it's going to work just fine so we even handle things like double quotes and commas which can be a challenge when exporting to csv because commas are obviously the delimiter for csv files we also support the option to include headers or to not include headers so that is the final result just a quick disclaimer this won't be supported in Internet Explorer the reason for that is because I'm going to be using things like classes and a few newer JavaScript features but you can quite easily modify this code to support Internet Explorer so let's go inside this tab right here it contains the same HTML without the export to CSV functionality so let's go inside the text editor and begin work on the Java scripts but first let's take a look at what we have going on so I've got here obviously just the HTML table with the table head table header row and also all of the data rows inside here it's also got an ID of data table and I've got the button down here export to CSV with an ID of BT and export to CSV so to begin that let's create a new directory called jeaious to store all of the javascript we can make a new file inside here and it's going to be called table CSV export jeaious and basically this would be a class responsible for doing the entire CSV exporting process so essentially the index file is going to be creating a new instance of the table CSV exporter and then from there we're going to pass in the actual table itself and then we can call a method on the table CSV export to of course export or convert the table to a CSV file so let's go ahead here and write a class we can say class table with CSV export and then you just start off by declaring all of the methods including the constructor so you can say constructor right here we're going to take in the table element itself and also an optional parameter to include headers so by default we are going to include headers in the CSV output okay so the main method is going to be called convert to CSV and this one is going to essentially do the main work for converting to CSV and this will take in no arguments because we're going to have access to the table through the constructor which we'll set as an instance property or instance variable so that's that one we can make one more or the second last one here it's going to be called find the longest row length and this will be considered to be a private method due to the underscore obviously in JavaScript you can actually make proper private methods but you can put an underscore and that's just a naming convention to signify it's going to be a private method and this one is going to essentially tell us the longest row length which basically means if we go back inside the example the longest row length for this table is going to be four as we have one two three four and that is the most amount of columns inside a single row so for us to go inside here and add a second a second table or sorry a fifth table data elements we now have five so in this case one two three four five the longest row length for this table is going to be five and the reason why we actually need this number is because when you export to CSV you need to basically make up for the longest row length even if some you'll rose don't have the maximum length so I'll just show you an example real quickly here so back inside this file if I was to add once again the extra column so I'll just go inside here and add that fifth one once again and then I can go inside here and actually export it so I'll just say new table CSV export I'm gonna pass in the data table just here I'm gonna say convert to seriously so this is what the final product will look like if I press ENTER here this is the output right so we can see here that for the row with the with the fifth column we can see that it does not have a comma whereas these ones do so these ones with four columns are going to have an extra v comma to make up for the extra row of sorry column inside this third one so that's why we need to know what the longest road length is okay so the fourth and final method is going to be a static method and it's going to be called pars itself it's gonna take in a table so the reason why it's a static method is because we don't need an instance of the table CSV export to parse a cell and pausing a cell basically means taking the text content of a table cell and then making it valid CSV so this will be dealing with all of the stuff like double quotes commas and line breaks to produce a valid sees the value okay so basically it's going to be applying the rules of a CSV file so now let's begin all this stuff right now by going inside the constructor and we can begin to implement this so the first thing we're gonna do is we're going to keep a reference to the table itself so we're gonna say this got table is equal to the table being passed in and this is going to be an HTML table element okay and secondly we're going to keep a reference to all of the rows inside the table so we can say this lot rose is equal to array and from and we can say table but really a selector or you can pass in here to you are so basically it's gonna be an array of all of the table row elements inside the table so I can just go down here I can console dot log lease and then go inside the index file and I can include the class jeaious for such export to CSV so our table of CSV exporter J yes and I can go down here now and get a reference to the table so I can say Const data table is equal to document dot get element by ID if I can spell it correctly so get element by ID passing here data table and then I can say new table with CSV export and parse in the data table to run the constructor remember I'm not going to be passing in a second argument here because we have true by default for the include header so I can save this and refresh the browser check the console and we have here table CSV export I'm forced to expand this we get here all of the four rows so one two three four and of course the actual data table itself so we can now work on the include headers parameter so basically we are going to be removing the first two row if we choose to not include the headers so we're going to say here if we wish to not include the headers and we actually sorry and we actually have a table header row and this can be done with this rows at index 0 that query selector all th dot link so basically if the length of this query selector is more than one and that means obviously if we actually have a th element inside the first table row then we can remove the first row so we can say this rows got ship and these shift method on the array is going to remove the first element so I can save this go inside this file and pass in false as the second argument and now we should only see three rows inside the console if I was to actions loggia this if I can save this refresh the browser once again and now we only get three rows we have one two three and they are all the data rows so that is the constructor fully implemented we can get rid of this and now we can work on defined and longest row length method so this one is going to simply run a binary juice on the array on the row zero so we can save return this rows we're going to reduce we're gonna have here the longest lengthier than a row I'm gonna say for each row if the road child element counts is greater than the occurrence of the longest row length then we are going to set the new row length to be Rho dot child element cap otherwise we're gonna use L and the default value here is going to be zero so basically the reduced method is going to take the rate and reduce it to a single value in this case we have for each row just check the current child element count it's basically gonna tell us how many table data rows sorry our table data elements are inside the table row if that is more than the current longest length then we can set that as the current and longest rolling otherwise we can use the existing one and a default value of zero for more info on the reduced method I have a whole video covering that method right there on arrays so that is defined longest row length method implemented so I might just go inside the constructor real quickly and just console dot log here the return value of the Phi and longest row length method so you can see what's happening so I can save this and refresh the browser and we get here for of course suppose to go inside the HTML and add a fifth column or even a sixth column to this I can save this and refresh and now it is six so that's how I'll be fun long as we're thinking method works I've given this stuff right there back inside here and now we can work on the pars cell method so as I said this one's basically gonna it's gonna be implementing all of the rules of a CSV file so we're gonna start here by saying let pass the value equal to table cell text content and we can go down here now so we're going to default be paused value to be the text content of the cell and now down here we can replace all of the double quotes with two double quote so we can say here place all double quotes with two parts so well with CSV files if you have a double quote as one of your values then you need to replace that double quote with two double quotes and that's just how double quotes are read in a CSV file format so we can say here positive value is equal to positive value replace are going to replace every instance of a double quote and make sure you use the the G flag for the regular expression and that will obviously replace all of the occurrences of the double quote we're going to a place full of those with of course the two double quotes so that does that job right there and secondly here basically if your sees the value contains either a comma a new line or a double quote you need to wrap the entire column in a double quote so in in double quotes so basically we're gonna say here if if value contains comma new line four double quotes then enclosed in double quote I hope that makes sense it's just basically following the rules of a CSV file so it can be read correctly without having any issues so we can go down here we can say past value is equal to we're going to test you we're gonna test and watch out for a double quote a comma or a newline character I'm gonna say dot test here we're gonna test the current past value if it contains any of these values we're gonna set the new past value to be double quotes and then we can pass in here our value otherwise if it's all good we just want to keep the current positive value but there are two the double quotes surrounding it and then we can return to be past ability and all this stuff right here is just to ensure we produce valid CSV so now we have these two methods done I might just once again similar to this one I'm gonna go inside the index file and actually call the pars cell method to you know actually damage that what's happening so I'm gonna go here I'm gonna say consult on log log table with CSV export dot has cell and I might need to actually for demonstration purposes I might need to just just get rid of this text content and just say positive value equals the value I pass in just to demonstrate this so now I'm gonna go back inside here and say parse it so I'm gonna type in here let's just say dumb and then a comma I can save this and refresh let me have this value so we can see that the return value has put double quotes around the text because I've got obviously that comma so I'll say this once again and say pass cell and now passing done without the comma this limit produces just the value with there I know this example isn't too good because obviously the console is adding in double quotes but I might go back inside here and just write that out with it out just like that save this refresh once again and now we get dumped here would no double quote so you can also test the actual double quotes so putting a double quote right there saving this and refreshing I mean y'all get the two double quotes and then the whole thing surrounded in double quotes so that is the pars cell method working correctly so now we can go ahead and implement the main public method and that one is going to be of course they convert to CSV so the way it's gonna work is are basically gonna be looking through each row inside the rows instance variable and then we're gonna be setting or we're going to be creating a string for each row and then appending that to an array of lines and then at the end we're gonna combine all of those lines with our line break and that will be a whole CSV file so we can say here constant lines is equal to an empty array we can also say Const num Coles is equal to this fine longer sprog link and then we can simply loop through all of the rows so we can say for constant row so for constant role of this rose so for each row we're going to sets a string variable right there called line and then we can basically loop through as many times as number of colors remember we need to have each each number of columns or the maximum amount of columns dealt with for every row regardless of the actual length so once again I'm gonna go inside here and just add an extra column for a better example let's copy this face of journey then once again money this method we can see now we get two double quotes we have one two three sorry two comments we have one two three four five commas even with empty values so days basically how we're going to be dealing with every single column based on the maximum column length of the paxil or longest road okay how'd that make sense let's go back inside here now and go inside the text editor and begin this work so we're gonna say for let's I equals zero I less than num holes I plus plus okay so in this case is going to be four so four times we're going to say if row children at index I does not equal undefined so this fight is basically checking do we have the value at this index so children is gonna be like a like a list of table data cells obviously all of these guys right here one two three four if we actually have a table cell at this index remember if you have in this case we have six if you get to the fourth one here the fifth index is going to be undefined so we're gonna check if we actually have a cell at this index then we can say line plus equals we can append to the lime string you can say table with CSV export dot parse cell we're gonna pass in here role children at index I and of course I forgot to actually change this back to be text content so let's put this back and yeah so that is that one all done now in all cases we are going to append a comma if we are not at the last column so we can say line plus equals we're gonna say if I does not equal num Coles - one so basically if we are at the last the last column in the loop then we can sorry if we are not at the last column in the loop we can append a comma otherwise don't append the comma if you're at the last column or index and finally we can say lines dot push and we can add the line to be lines array and then we can simply return lines join we're passing here a line break so that is the entire convert to CSV function done and as you can see here this is basically bits it's going to be producing for you a string of basically CSV so now we can use this method let's go back inside the index file and actually just say dot convert to CSV and we can console.log this return value I can save this and refresh and we have this result right here we have the CSV file working or not see here for things like Jeff the champion Foster we have the double quotes and in the output we can see it's been replaced with the two double quotes and same goes for when you have a comma so whenever comma obviously the double quotes gets surrounded all the content gets fan of our double quotes so it's all working fine and for cases where the text isn't too special we don't have any double quotes surrounding it so this is all about that CSV and it's going to open in just about any csv viewer so we can go and just test the maximum column length thing so you can duplicate a table data cell here save this and refresh and now we can see here we get the extra comma to make up for that fifth column so it's all working just fine so now we can basically make a call to the exporter and actually download the CSV file so to do this we're going to be creating a blob and from there we're gonna be getting a reference to the blob and then we can just download it virtually or sorry we can download it by virtually clicking on an anchor element so let's get rid of this stuff and make a new constant for the bTW and export to CSV I know the whole blob thing sounds a bit complicated but honestly it's not too complex at all so I'm gonna get a reference to the BT and export to CSV button and from there we can say BT and export to CSV dot add eventlistener when a button gets clicked on we're gonna run this function inside here so the function is gonna do obviously all of that process right there so let's first create a new exporter so you can say concerts exporter equal to equal to a new table CSV export we're gonna pass in here the data table and they're going to include headers by default we can make a new constant for the CSV output equal to exporter dots converts to CSV call this one output not outputs there we are and we can now create the blob so a blob is basically just a container for random data so in this case we're going to be creating a blob of CSV so we can say here cost CSV blob is equal to a new blob and the blob constructor takes in an array so can pass in here an array and pass in a CSV output as the only element inside the array and as the second argument here we can say type is text seriously so basically we're creating a blob it's a container of data for the CSV output and as a type of text slash CSV so from there we can get a reference to the actual blob so we can say consul of inurl is equal to URL to create object URL and this will accept a blob so they can say seriously blob so basically what's happening here is the return value of this is basically this right here Fabrice Xbox CSV it's this right here so a blob at this address so it's like a little internal reference to the blob and this is actually downloadable by the end user so with that with that being said we can go inside here and simply at the moment you can just console dialogue we'd love you oh I'll save this and refresh the browser we can press export to CSV and we get here the blob so this right here is a reference to the actual blob contain the contents and it is downloadable by the clients web browser so with that being said we can now create a new a Aker element and have the href set to the blob and that is then downloadable so I can go back inside here make a new constant for this one anchor element equal to document creates element you're going to put inside here a okay so of course making a new a element then we can simply say anchor elements dot H ref is equal to the blob URL alrighty we can say anchor element download so the download attribute is basically the name of the file that the user will be downloading if you don't add the download attribute then they're gonna be downloading a file called one sixty eight to nine four etc so to prevent them from downloading this random string of characters you set the download attribute to be something readable such as table export dot CSV all right cool and then we can simply say element clip so calling the click method on this element is basically going to virtually click on the hidden anchor element the last thing to do here is to say set timer and they're going to timeout this function right here we're going to say URL can revoke object URL we can pass in here the blob URL so the revoke object URL is going to be telling the browser to forget about the reference to the blob if you don't do this you may be increasing them reduce it so just do this to reduce the amount of memory being used by the browser and we can say 500 right here and the reason what this is inside a set timeout is because on Microsoft edge I've found that if I don't use a a timeout then the follow download won't actually start so to ensure the download to work on Microsoft edge ensure you have the the timeout right there so I can save this and refresh the browser and we have here our final result if I was to refresh this press export to CSV and we get here the CSV output working just fine alright and I can also just go inside here and I can say false to the include headers argument save this and refresh press export and now we get the output without the header row and that is how you can export an HTML table to a CSV file using plain JavaScript any questions please leave a comment asking thanks for watching guys and I'll see you later
Info
Channel: dcode
Views: 28,151
Rating: undefined out of 5
Keywords: code, coding, programming, tutorial, introduction, beginner, walkthrough, guide, software, development, simple, easy, into, english, with, example, examples, developer, lecture, recording, web, website, app, application, export, convert, to, parse, compile, csv, comma, separated, file, excel, exporting, table, tables, html, html5, php, nodejs, node, python, download, automatically, blob, blobs, object, objecturl, url, createobjecturl, revoke, revokeobjecturl, classes, class, constructor, public, private, static, method, ecmascript2015, es6, project
Id: cpHCv3gbPuk
Channel Id: undefined
Length: 28min 8sec (1688 seconds)
Published: Mon May 13 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.