
Export Table Data to an Excel Spreadsheet #25
Chapter 3, Tables and Trees
|
131
HACK
Dealing with Formatting
Excel uses a complicated database-oriented format for its native .xls files.
This format defines the formulas, colors, charts and every other advanced
feature Excel has supported over the years. Writing to the native .xls format
is complicated but, fortunately, Excel supports other formats. The one I’m
going to target is known as a tab-delimited text file, so called because tabs
separate each field. This format is just plain text, so it will be super easy to
write from Java, and open up in Excel with just a double-click.
Tab-delimited files separate each field with a tab character and each row
with a standard Unix line break,
\n
. Since Swing defines a convenient
getValueAt( ) method in the TableModel interface, it’s very easy to just loop
through the table cells and write it out to a file, as seen in Example 3-14.
This code defines an
ExcelExporter class with a single method exportTable( ),
taking a
JTable and a file. All JTables contain an implementation of the
TableModel interface that holds the actual data. The code first retrieves the
table model and opens a new
FileWriter to the file. I used a FileWriter
instead of a FileOutputStream because Writers automatically handle text
encoding issues. This means you don’t have to worry about the language the
program is running on. Using a
Writer ensures ...