5
\$\begingroup\$

I have written this class that will write a JTable to a tab delimited file so that it can be opened in Excel. It works great, but is there any way to make it better or have it directly open in Excel without having to go through the import screens all of the time? How can I tidy up this code to work or operate more efficiently?

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableModel;

public class excel {
    String columnNames[] = { "Column 1", "Column 2", "Column 3" };
    String dataValues[][] =
    {
        { "12", "234", "67" },
        { "-123", "43", "853" },
        { "93", "89.2", "109" },
        { "279", "9033", "3092" }
    };

    JTable table;

    excel() {
        table = new JTable( dataValues, columnNames );
    }


    public void toExcel(JTable table, File file){
        try{
            TableModel model = table.getModel();
            FileWriter excel = new FileWriter(file);

            for(int i = 0; i < model.getColumnCount(); i++){
                excel.write(model.getColumnName(i) + "\t");
            }

            excel.write("\n");

            for(int i=0; i< model.getRowCount(); i++) {
                for(int j=0; j < model.getColumnCount(); j++) {
                    excel.write(model.getValueAt(i,j).toString()+"\t");
                }
                excel.write("\n");
            }

            excel.close();

        }catch(IOException e){ System.out.println(e); }
    }

    public static void main(String[] o) {
        excel cv = new excel();
        cv.toExcel(cv.table,new File("H:\\cs.tbv"));
    }
}
\$\endgroup\$
0

2 Answers 2

5
\$\begingroup\$

Most of the issues with this code are stylistic and violations of Java conventions rather than functional.

public class excel {

Class names should always be capitalized (e.g., public class Excel). Your class should probably also be named more descriptively and appropriately. Your class isn't Microsoft Excel. It's a class which converts JTable data into a CSV. So it would make more sense to name your class JTableConverter or something like that.

String columnNames[] = { "Column 1", "Column 2", "Column 3" };

Class fields should always have an explicit access modifier (public, private, or protected). Generally, if they're constants (as you use them), they are either public static final or private static final with the name in ALL_CAPS_WITH_UNDERSCORES. For an understanding of static, you can see this StackOverflow Q&A.

So... private static final String[] COLUMN_NAMES = { "Column 1", "Column 2", "Column 3" };

excel() {
    table = new JTable( dataValues, columnNames );
}

Constructors and methods should also have an explicit access modifier. (public JTableConverter())

public void toExcel(JTable table, File file) {

Method names should generally be verbs or verb phrases (such as convertToExcel). Also, since you're passing in the JTable to be used, it would make more sense for this to be a static method rather than an instance method. If you want it to be an appropriate instance method, there's no need to pass in the JTable at all, since the instance will already have access to the JTable table field.

excel.close();

Releasing or closing resources should pretty much always be done in a finally block, which is guaranteed* to run. i.e.,

FileWriter writer = new FileWriter(file);
try {
    //stuff
}
catch(IOException ioe) {
    //handling
}
finally {
    try {
        writer.flush();
        writer.close();
    }
    catch(IOException ioe) {
        //handling
    }
}

And, finally ...

public static void main(String[] o) {
    excel cv = new excel();
    cv.toExcel(cv.table,new File("H:\\cs.tbv"));
}

It's a bit nitpicky, but it's usually better to have your main method in a separate driver class (like JTableConverterDriver).

\$\endgroup\$
2
  • \$\begingroup\$ If he's using Java 7, he should use the try-with-resource statement, it will close automaticly. \$\endgroup\$
    – Marc-Andre
    Commented Mar 2, 2014 at 22:41
  • 1
    \$\begingroup\$ @Marc-Andre Very true. Too used to coding in Java 6. That's what I get for spending the majority of my time coding for big companies that take years to adopt change, haha. \$\endgroup\$
    – asteri
    Commented Mar 2, 2014 at 22:43
2
\$\begingroup\$

is there a way to have it directly open in Excel without having to go through the import screens all of the time?

The easiest way may be:

  • Use comma-delimited instead of tab-delimited
  • Make the extension "csv" instead of "tbv"
  • See here for how to escape commas
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.