Java swing exports data in jtable to excel

Source: Internet
Author: User
Paste the Code directly.
Import java. AWT .*;
Import java. AWT. event .*;
Import java. Io .*;
Import javax. Swing .*;
Import javax. Swing. Table .*;
Public class excelexporter {
Public excelexporter (){}
Public void exporttable (jtable table, file) throws ioexception {
Tablemodel model = table. GetModel ();
Filewriter out = new filewriter (File );

For (INT I = 0; I <model. getcolumncount (); I ++ ){
Out. Write (model. getcolumnname (I) + "/t ");
}
Out. Write ("/N ");
For (INT I = 0; I <model. getrowcount (); I ++ ){
For (Int J = 0; j <model. getcolumncount (); j ++ ){
Out. Write (model. getvalueat (I, j). tostring () + "/t ");
}
Out. Write ("/N ");
}
Out. Close ();
System. Out. println ("write out to:" + file );
}


Public static void main (string [] ARGs ){
String [] [] DATA = {
{& Quot; housewares & quot;, & quot; $1275.00 & quot "},
{& Quot; pets & quot;, & quot; $125.00 & quot "},
{"Electronics", "$2533.00 "},
{"Mensware", "$497.00 "}
};
String [] headers = {"department", "daily revenue "};

Jframe frame = new jframe ("jtable to excel hack ");
Defaulttablemodel model = new defaulttablemodel (data, headers );
Final jtable table = new jtable (model );
Jscrollpane scroll = new jscrollpane (table );

Jbutton export = new jbutton ("Export ");
Export. addactionlistener (New actionlistener (){
Public void actionreceivmed (actionevent EVT ){
Try {
Excelexporter exp = new excelexporter ();
Exp. exporttable (table, new file ("results.xls "));
} Catch (ioexception ex ){
System. Out. println (ex. getmessage ());
Ex. printstacktrace ();
}
}
});

Frame. getcontentpane (). Add ("center", scroll );
Frame. getcontentpane (). Add ("South", export );
Frame. Pack ();
Frame. setvisible (true );
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.