Translate CSV To HTML

Question is from here:

A common format for data storage is the CSV format for comma-separated values. A common format for data presentation is HTML for browsers using tables.

Your task is to write a function that reads a file in CSV format and translates it to a table in HTML format.

The CSV file looks like this:

Beth,12.75,0,mfg
Dan,8.50,10,sales
Kathy,11.40,30,sales
Mark,12.75,40,mfg
Mary,7.50,20,mfg
Susie,10.30,25,acctg

My Solution:
After reading the file, each line is stored inside a map (line). When all the lines are read, a HTML file is created and we start writing HTML tags into this file.

For each line, <tr> tag is inserted.
String of each line is splitĀ at each comma.
A <td> tag is inserted for each word.

Please note to change file location according to the place of file in your computer.

import java.io.*;
import java.util.*;

public class Translate_CSV_To_HTML {
	public static void main(String[] args) throws IOException {
		//read file
		File file = new File("test.csv");//file location
		//store each line, Integer is the line number and
		//String stores each line
		Map<Integer, String> line = new HashMap<Integer, String>();
		int lineCounter = 0;
		String l = null;//to store current line
		BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
	
		try {
			while((l = bufRdr.readLine()) != null) {
				//read current line and put it into the map(line)
				line.put(lineCounter++, l);
			}
		} catch (IOException e) { e.printStackTrace();}
		
		//write to html file
		String[] parts;
		FileWriter fstream = new FileWriter("test.html");
		BufferedWriter out = new BufferedWriter(fstream);
		
		out.write("<html>");
		out.write("<table>");
		for (Map.Entry<Integer, String> entry : line.entrySet()){
			parts = entry.getValue().split(",");
			out.write("<tr>");
			for (int i = 0; i < parts.length; i++) {
				out.write("<td>");
				out.write(parts[i]);
				out.write("</td>");
			}
			out.write("</tr>");
		}
		out.write("</table>");
		out.write("</html>");
		out.close();		
	}
}

Output:

<html><table><tr><td>Beth</td><td>12.75</td><td>0</td><td>mfg</td></tr><tr><td>Dan</td><td>8.50</td><td>10</td><td>sales</td></tr><tr><td>Kathy</td><td>11.40</td><td>30</td><td>sales</td></tr><tr><td>Mark</td><td>12.75</td><td>40</td><td>mfg</td></tr><tr><td>Mary</td><td>7.50</td><td>20</td><td>mfg</td></tr><tr><td>Susie</td><td>10.30</td><td>25</td><td>acctg</td></tr></table></html>

And it looks like this:

Beth 12.75 0 mfg
Dan 8.50 10 sales
Kathy 11.40 30 sales
Mark 12.75 40 mfg
Mary 7.50 20 mfg
Susie 10.30 25 acctg
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s