Mar 07

Displaytag is a great tag library for rendering data as a table. As well as handling the generation of the html table, it also provides support for easily exporting the table to a variety of formats including Excel (and CSV).

One problem that can occur is Excel formatting the table cells. When it sees a value that looks like a number then it attempts to format it as a number. This can result in values being displayed in Excel in scientific notation when you really want the data to be displayed as is.

To fix this we can use a displaytag column decorator that quotes the values when exporting to Excel. That way excel will see the quoted value and no longer think it as a number and display it without formatting as you require.

import javax.servlet.jsp.PageContext;
import org.displaytag.decorator.DisplaytagColumnDecorator;

public class QuotedExportDecorator implements DisplaytagColumnDecorator {
    public Object decorate(Object value, PageContext pageContext, MediaTypeEnum media) {
        if (media.equals(MediaTypeEnum.EXCEL) || media.equals(MediaTypeEnum.CSV)) {
            value = "=\"" + value + "\"";
        return value;

written by objects \\ tags: , , , ,

May 25

If you have a CSV (or TSV) that you need to display in a JTable then you should have a look at the TableModelExtTextLoader class from SwingLabs.

It provides all you should need and save you the hassle of reinventing the wheel and using a half baked CSV implementation.

Here is an example of it’s usage.

URL csv = new URL("http://myapp/employees.csv");
DefaultTableModelExt data = new DefaultTableModelExt(url);
TableModelExtTextLoader loader = 
        new TableModelExtTextLoader(",", false, 75);

As many of you will probably have a file from disk that you want to load then see “How to convert a File to a URL”

written by objects \\ tags: , , ,