Saturday, September 5, 2009

HTML Table to CSV

Here is a simple JavaScript to convert HTML table to CSV.


function createCSV(tableId) {

var tbl = document.getElementById(tableId);

if (tbl == null) return;

var trs = tbl.getElementsByTagName("tr");

var csv = '';
for (var j = 0; j < trs.length ; j++ ) {
var c = trs[j].cells;

for(var i= 1; i < c.length ; i++ ) {
if (i > 1) csv = csv + ',';
csv = csv + '"' + c[i].innerText + '"';
}
csv = csv + '\n';
}
document.getElementById('debug').value = csv;
}


Thursday, November 29, 2007

Copy directory structure using ANT

Here is a simple way to copy a complex directory structure to a new location.

May a times we would have faced this kind of requirement. A complex directory system with lot of files in it. And you want to copy only the directory structure not any files. If you are familiar with Apache ANT, there is a simple way to do this.

<project name="COPY" default="copy.only.dir" basedir=".">

<property name="source.dir" value="<sourceDir>"/>
<property name=" dest.dir" value="destinationDir"/>

<target name="copy.only.dir" depends="">
<copy todir="${dest.dir}">
<fileset dir="${ source.dir}">
<type type="dir"/>
</fileset>
</copy>
</target>

</project>

Save this XML to build.xml , change the source and destination directories and run ANT (from command prompt just type ant. This should be done from the directory where you have saved the build.xml)

Simple, but useful. Isn't it?

Friday, November 23, 2007

CSV to XML Conversion

A simple CSV-to-XML Converter. This is just a proof-of-concept. We can add lot of flush into it depending upon the requirement. Concept is simple. Along with the CSV file (data), provide another file with xml tags corresponding to each field in the CSV file. Read line by line from the CSV data file and prepare the XML nodes using the tag file.

Sample CSV data file
1, Bill Clinton, 56, President, United States of America
2, Sonia, 55, CEO, ABC Limited

Sample CSV tag file
id, name,age, designation, company

Source Code

public String generateXML(String tagFile, String sourceFile) {
StringBuffer buf = new StringBuffer();

String tagLine = "";
String dataLine = "";
//read tagFile and get the line
String []tags = tagLine.split(",");

buf.append("<" + rootTag + ">\n");
//read Source file and read line by line and invoke generateXMLNode.
while (....) {
buf.append(generateXMLNode(tags, dataLine));
}

buf.append("");
return buf.toString();
}

public String generateXMLNode (String []tags, String data) {
StringBuffer buf = new StringBuffer();
String []dataElements = data.split(",");

buf.append("\t<" + nodeTag + ">\n");
for (int i = 0; i <>");
buf.append(dataElements[i]);
buf.append("\n");
}
buf.append("\t<" + nodeTag + ">\n");
return buf.toString();
}

There is no proper standard for CSV. Here I have taken a simple CSV file, but in actual cases may have coma and carriage returns inside the data elements.