Files
Java_Examples/pickMaint/ExcelExporter.java
T

63 lines
1.7 KiB
Java

package pickMaint;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.TableModel;
/**
* This class provides means to dump the contents of a JTable into a tab delimited file and then open it in Excel.
*
* @author Wesley Ray
*/
public class ExcelExporter {
private static final Logger LOGGER = Logger.getLogger(LoomDSRecord.class.getName());
/**
* Dumps the data in a JTable out to a tab delimited file.
* @param table
* @param outFile
* @throws IOException
*/
public static void exportJTableToFile(JTable table, String outFile) throws IOException{
TableModel m = table.getModel();
FileWriter out = new FileWriter(outFile);
String buffer = "";
LOGGER.info("Exporting " + m.getRowCount() + " rows to tab delmited file: " + outFile);
for (int i = 0; i < m.getColumnCount(); i++) {
buffer += (m.getColumnName(i) + "\t");
}
out.write(buffer + "\n");
buffer = "";
for (int i = 0; i < m.getRowCount(); i++) {
for (int j = 0; j < m.getColumnCount(); j++) {
buffer += (m.getValueAt(i, j) + "\t");
}
out.write(buffer + "\n");
buffer = "";
}
out.flush(); //Make sure everything gets written
out.close(); //Close the file
out = null; //Make sure this gets garbage collected
}
/**
* This only works on Windows. This will work with any file that you can double click to open really.
* XLS files happen to open in excel automatically.
*
* @param path
* @throws IOException
*/
public static void openInExcel(String path) throws IOException{
LOGGER.info("Invoking \"cmd.exe /c start " + path + "\"");
Runtime.getRuntime().exec("cmd.exe /c start " + path);
}
}