9 May 2011

Java Swing -Export JTable To Excel File


Java Swing - Export JTable To Excel File


Run The Code and you get this JFrame.




Output In Exported Spreadsheet File




______________________________________________________________

Write ExcelExporter Class:-



import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.*;
import javax.swing.table.*;

import jxl.*;
import jxl.write.*;

public class ExcelExporter {

    void fillData(JTable table, File file) {

        try {

            WritableWorkbook workbook1 = Workbook.createWorkbook(file);
            WritableSheet sheet1 = workbook1.createSheet("First Sheet", 0);
            TableModel model = table.getModel();

            for (int i = 0; i < model.getColumnCount(); i++) {
                Label column = new Label(i, 0, model.getColumnName(i));
                sheet1.addCell(column);
            }
            int j = 0;
            for (int i = 0; i < model.getRowCount(); i++) {
                for (j = 0; j < model.getColumnCount(); j++) {
                    Label row = new Label(j, i + 1,
                            model.getValueAt(i, j).toString());
                    sheet1.addCell(row);
                }
            }
            workbook1.write();
            workbook1.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String[][] data = {{"Housewares", "Rs.1275.00"},
            {"Pets", "Rs.125.00"}, {"Electronics", "Rs.2533.00"},
            {"Menswear", "Rs.497.00"}
        };
        String[] headers = {"Department", "Daily Revenue"};

        JFrame frame = new JFrame("JTable to Excel");
        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() {

            @Override
            public void actionPerformed(ActionEvent evt) {

                try {
                    ExcelExporter exp = new ExcelExporter();
                    exp.fillData(table, new File("C:\\result.xls"));
                    JOptionPane.showMessageDialog(null, "Data saved at " +
                            "'C: \\ result.xls' successfully", "Message",
                            JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

        frame.getContentPane().add("Center", scroll);
        frame.getContentPane().add("South", export);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    }
}
______________________________________________________________

Here When you Click on Export Button then whole JTable Data will be transfered to result.xls file in your C Drive.....

So try & Enjoy.........

Leave Comments if you like.....
Thank you....

58 comments:

  1. Thank you very much!!!! it helps me a lot!!!!!!!!!!!!!!

    ReplyDelete
  2. Made my day, oh my night lol, Thanks

    ReplyDelete
  3. thanks a lot, it has really helped me..

    ReplyDelete
  4. Thank you so much it helped a lot ... can you post excel to jtable exporter
    ?

    ReplyDelete
  5. Hi Anonymous, I will try to fulfill your requirement regarding excel to jTable exporter.

    ReplyDelete
  6. Hi , great example.. but if i want to add a show button that loads to jtable the same data saved to .xls file by your example , how can that be done? thanks in advance

    ReplyDelete
  7. Hi, Hope, thanks for your comment. I have analyzed your problem and solved your problem regarding loads excel file data back in JTable. I have posted one new post called "Import Excel Data into JTable " regarding this problem. Please check it and tell me is it ok..?

    ReplyDelete
  8. Hi i just saw your comment... i will check the code now , Thank you so much

    ReplyDelete
  9. Hi Mr Nirav .. i added fill data method in my code but im getting this exception :
    jxl.read.biff.BiffException: Unable to recognize OLE stream ..
    ...
    to show you what im doing , i have this show button :
    else if (event.getSource() == showb){

    Vector data = new Vector();
    data.clear();
    FinalExport fexp= new FinalExport();
    data= fexp.fillData(new File("d:\\Factories.xls"));

    model.addRow(data);

    }

    ///// this file Factories.xls is the one that i created with your code from jtable .. now when i open it again from your new code i used it like this :public class FinalExport {

    Vector fillData(File file) {
    Workbook workbook = null;
    Vector data = new Vector();

    try{
    System.out.println("here 1");

    try {
    workbook = Workbook.getWorkbook(file);
    System.out.println("here 2");

    } catch (IOException ex) {
    Logger.getLogger(
    FinalExport.class.
    getName()).log(Level.SEVERE,
    null, ex);
    }
    Sheet sheet = workbook.getSheet(0);
    data.clear();
    for (int j = 1; j < sheet.getRows(); j++) {
    Vector d = new Vector();
    for (int i = 0; i < sheet.getColumns(); i++) {

    Cell cell = sheet.getCell(i, j);

    d.add(cell.getContents());

    } // end of for1
    d.add("\n");
    data.add(d);
    } // end of for2
    System.out.println(data);
    } catch (BiffException e) {
    e.printStackTrace();
    }
    return data;
    }
    }


    ///// but i get an exception .. what am i doing wrong?
    sorry for my long reply

    ReplyDelete
  10. Hi Hope,
    For exception "Unable to recognize OLE stream ", Please Save As your Excel file in Windows 97-2003 XP format. Because jxl.jar does not provide support for any other excel version as I know.

    Try this. I hope your problem will be solved.
    And if you find any other solution then please share with me.

    Thanks....

    ReplyDelete
    Replies
    1. I could NOT located jxl.jar file. Can you please help

      Delete
    2. Hi you have to import external jar file "jxl.jar" in your eclipse project. If you do, you will definitely compile this code. Please explain if this is not the case..!

      Thank you.

      Delete
    3. Where Do I find this jxl.jar file. Where do i download this jar so I can add it to my eclipse project? thanks for youe help. all you projects are very useful and informative

      Delete
    4. Hi Kiran, Please follow link
      http://www.findjar.com/jar/net.sourceforge.jexcelapi/jars/jxl-2.6.jar.html

      In above link find another link for download-
      http://mirrors.ibiblio.org/pub/mirrors/maven/net.sourceforge.jexcelapi/jars/jxl-2.6.jar

      When you want to download any jar fle just type in google with download keyword like for this jar write - "jxl.jar download". And you will get links for that.

      Delete
    5. Thanks again Nirav. Since you posted this code, I assumed you also wrote the jar file and was searching on your blog. Spent lot of time looking here only. Also, Is Swing widely used for GUI I was also told that JSF is also used and easy. I'm relatively new and still learning.

      Delete
    6. Hi Kiran, first thanks for comment. I hope you found the jar from above posted link. Off-course, Swing is widely used GUI in Desktop based application. JSF is new technology which is widely used in web based application. So both are different. You should first learn both in time. But first get expertise over core java, because it is the core part of any JAVA technology. So all the best from my side.
      Thank you...!

      Delete
    7. Thanks again, i was able to donwload the jar file and also sucessfully run the code. I would like to see the excel workbook open and do the export rather than doing behind the scenes and save if i need to save. I guess i need to chekc .jar files API to do this?

      Delete
  11. Hi Hope,
    I think you are using linux. So you have Open Office...right..? Just save as your excel file as "Microsoft Excel 97/2000/XP(.xls)" format.

    Then simply run the current code.....

    ReplyDelete
  12. OOh , then the file i created by your code above can not be opened by your next code until its saved as again in Windows 97-2003 XP format ... thats a problem because i combined both codes in one program to add data,save it , and then show it again :(

    ReplyDelete
  13. Sorry for bothering you but last question Is there away to choose the format of the file ? to save it as Windows 97-2003 XP format from the first place?

    ReplyDelete
  14. Sorry for bothering you again and again ... but last question is there away to set the file format to Windows 97-2003 XP format when saving from jtbale to excel so i can open it immediately bu exceltoJtable code ? or away to solve this problem ? or should i work on another way for saving and reading ? thanks

    ReplyDelete
  15. Hi Hope,
    Don't be sorry for bothering me...I feel good that my efforts are useful to others..

    Now I saw your comment and based on that I have developed one new code which will directly save the data in Microsoft 97-2003 XP format. So now I hope your problem is solved.

    Just refer the above Post of "Java Swing - Export JTable To Excel File"

    Thank you...

    ReplyDelete
  16. Hi Nirav :) thank you so much for your help, really you solved my problem i finished my project thanks to you :) Best programmer

    ReplyDelete
  17. Its my Pleasure Hope! Thanks....

    ReplyDelete
  18. me again :) just a thing i am facing .. i am using eclipse and as i told you the project finished and running fine in eclipse .. i exported it to jar now it doesn't function read or write from excel but in eclipse it does , how come ?

    ReplyDelete
  19. sorry dont bother your self i solved it i had to add a plugin thnx

    ReplyDelete
  20. hi nirav..
    i have a jtable, but i made it using a JFrame Form..
    not just a java class..
    i am using netbeans btw..
    my program builds successfully
    but when i open the file the file seems to be corrupted
    the datas on my jtable can't be exported to the excel file...
    i hope you would understand.. i can't explain it very well..
    thanks for your help.. :)

    ReplyDelete
  21. Sir,
    i am making an application in net beans with backend as MS sql server 2008...I am facing the same problem , i am not able to convert the data shown in JTABLE to excel file or even PDF for that matter please help me looking for early reply...

    Thankyou.....

    ReplyDelete
  22. Excelente ayuda. Muchas gracias, me sirvió mucho para el proyecto que estoy realizando.

    ReplyDelete
    Replies
    1. Hola Anónimo, me alegra saber que mis obras son útiles a los demás. Gracias por tu comentario agradable.

      Delete
  23. Thank you! It works great! Maybe you should add a couple of lines in case a field in the jtable is null , in order not to have exception of null pointer. I came over to this problem with my code because some fields of my jtable need to be empty so here is my solution that you can add.
    String theValue= new String();
    int j = 0;
    for (int i = 0; i < model.getRowCount(); i++)
    {
    for (j = 0; j < model.getColumnCount(); j++)
    {
    if ( model.getValueAt(i, j)!=null)
    {
    theValue= model.getValueAt(i, j).toString();
    }
    else
    {
    theValue=" ";
    }

    Label row = new Label(j, i + 1, theValue);
    sheet1.addCell(row);
    }
    }

    ReplyDelete
  24. Hi, can we import data from excel and put into jTxxtArea??

    For,example I want to put the A1 into jTextField1 A2 into jTextField2 and etc..

    ReplyDelete
  25. Hi, can we import data from excel and put into jTextArea??

    for example, I wan to put A1(from excel) into jTextField1 , A2 into jTextField2 and etc..

    Thanks

    ReplyDelete
  26. Hi Shankar Here i want to create a tool.

    i.e i want to export data from excel sheet..
    export data is like Person Bio..

    then in the tool i want to split the Bio in diff fields..

    have to parse it.

    then i want to save the file in excel sheet pls reply me and give some ideas..Thank you.

    ReplyDelete
    Replies
    1. You are doing good job. Keep it up. For your tool which requires to import data from excel sheet to JTable is totally reversed process from the above post. Try to figure it out. Here you need to identify all the sheets in excell and each cell of excel to fetch data from it into jTable.

      I will put new post for this in very near future.
      Thank you.

      Delete
  27. Excellent work

    ReplyDelete
  28. hey..the code works perfect. :)
    But there is one problem...everything is exported as string from the table..so calculations cannot be performed..plss help.
    I am filtering data from excel sheet to jTable n storing the result in a new excel sheet. Ive refered to both of your import from excel and export to excel codes. but i would like the data type to remain same in both jtable n new excel sheet.

    plss tell the modifications as i need to complete my project.
    thanx

    ReplyDelete
    Replies
    1. Hi, I understand your query...Here you have to use instanceof operator of Java. Now, first get all values from excel sheet in Vector with Object type rather than String. Then check each value with instanceof to identify if it is Integer or String or Character etc... I can not tell you complete code right now. But try to play with instanceof operator. It will identify the object type and u can perform the operation based on that type...
      Best of luck...
      Thank you for your comment...

      Delete
  29. Hello, your code is great, mainly just what I need, but I have some questions. Is there a possible way to set the size of the excel columns? I have a table which should have fixed width columns. In one of the columns, the information will be very long, so I need the column to be smaller such that it forces the info to go on 2 or 3 rows. Also, I want to display something before the table: some basic info like a name of a company in the top left corner, some info for it and a title which should be displayed on the middle right before the table. Also, this info needs o be written with a cvertain font (larger, bold and underlined). Is that possible? And also, is it possible to write from code (java) the information mentioned above, with the specified requirements, to apear before the table without lines, and the table to have lines which show the table structure, when printing the excel document?

    ReplyDelete
  30. thanks. got my quick fix for table exporting.

    ReplyDelete
  31. Thanks Nirav, this is really helpful for me to learn. Works great once you add the jar file.

    ReplyDelete
  32. ExcelExporter exp = new ExcelExporter(); ??? error?? what i should do??

    ReplyDelete
    Replies
    1. Hi, Fajar. Can you post the error. So I can understand the error you facing. First make sure you add jxl.jar in your project.

      Delete
  33. Very nice example :) Really very helpful :)
    Thanks a lot :)

    ReplyDelete
    Replies
    1. Thanks Ashwini! I hope you enjoyed the tutorial.

      Delete
  34. Hi Nirav, I have created a JTabbed Pane. In one of the Tab there is a container containing a JButton. Now I want to import data from excel to Jtable, placed in another tab, when I clicked on the JButton.

    ReplyDelete
  35. Genial! Muchas gracias por compartir tu sabiduría!

    Me ha servido de mucho y funciona perfecto!

    Un saludo

    ReplyDelete
    Replies
    1. Mi placer Rubén. Me alegro de que te gustaban mis esfuerzos.

      Delete
  36. Dear Mr. Raval,

    I ended up here after struggling with excel and its impossibility to import data from dynamic Jtables using query function. Could you please help me out here, I am just a beginner in Java. If I have a web page which has a dynamic table in it I can use your code in order to import that table to a sheet? Thank you in advance

    ReplyDelete
  37. Hey Nirav,

    If i try to change the path to where i want the file to be saved, i get an error:"Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )"
    How can i avoid this error. the location that it should be is "C:\JAVA".

    Kind regards
    Pieter van Heijst

    ReplyDelete
    Replies
    1. Hi Pieter,
      You should write as "C:\\JAVA" Or "C:/JAVA" instead of
      "C:\JAVA".

      Delete
  38. Thanks so muaccchhhhh

    ReplyDelete
  39. I have exported to excel sheet single table data,but i want to add multiple table data in single excel sheet please help me out....

    ReplyDelete
  40. Hi Nirav,

    This tutorial worked fine,adding single jtable data to excel fine,i tried to add multiple jtable data in single excel sheet didn't work properly overwrites the table cell please help me out..

    ReplyDelete
  41. Hi nirav, the problem with me is, i downloaded the jxl.jar file but yet it is showing the error cannot imort jxl.*;
    can u please help me out for this, & one more thing i need to ask is i need to export 29 columns and n no. of rows of Jtable to Excel, will you please help me out with my problem, my submissions are in nxt 2 days, please if you can get back soon.. thank you..

    ReplyDelete
  42. i have this program in java swing jframe, when i click on print it should be saved to an excel file. can you pls help me on this..

    import java.sql.*;
    import javax.swing.*;
    import java.util.Date;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    class shops_report extends JFrame {
    public Container content;
    public JPanel reportingPanel;
    public JTabbedPane listsTabs;
    public JTextArea listPane;
    public JPanel reportPanel;
    public JPanel statusPanel;
    public JComboBox graphTypesCombo;
    public Color skyblue = new Color(150, 190, 255);
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    Statement stmt = null;
    JButton print,cancel;
    JPanel panel;
    public shops_report() {
    content = getContentPane();
    content.setBackground(skyblue);
    listsTabs = new JTabbedPane();
    print = new JButton("Print");
    cancel = new JButton("Cancel");
    panel = new JPanel();
    panel.add(print);
    panel.add(cancel);
    reportingPanel = new JPanel();
    reportingPanel.setLayout(new BorderLayout());
    reportingPanel.setBorder(BorderFactory.createEtchedBorder());
    reportingPanel.add(new JLabel("Shops Report Summery"), BorderLayout.NORTH);
    reportPanel = new JPanel();
    reportPanel.setLayout(new GridLayout(1, 1));
    reportPanel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.blue));
    reportPanel.setBackground(Color.white);
    reportingPanel.add(new JScrollPane(reportPanel), BorderLayout.CENTER);
    reportingPanel.add(panel, BorderLayout.SOUTH);
    listsTabs.add(reportingPanel);
    setLocation((screen.width - 1270) / 2, ((screen.height - 740) / 2));
    setResizable(false);
    listPane = new JTextArea() {
    { setOpaque(false); }
    public void paint(Graphics g) {
    super.paint(g);
    }
    };
    listPane.setEditable(false);
    listPane.setFont(new Font("Serif", Font.BOLD, 12));
    listPane.setForeground(Color.black);
    listPane.setLineWrap(true);
    listPane.setWrapStyleWord(true);
    reportPanel.add(listPane);
    print.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) { } });
    try {
    Statement s = DBConnection.getDBConnection().createStatement();
    } catch (Exception excp) {
    excp.printStackTrace();
    }
    printList();
    content.add(listsTabs, BorderLayout.CENTER);
    cancel.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {
    dispose();
    }
    });
    setSize(1000, 720);
    setVisible(true);
    }
    private void printList() {
    try {
    ResultSet rst = DBConnection.getDBConnection().createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE).executeQuery("select NAME,BATCH_NO,STOCK_AVAIL,STOCK,BILL,PAYMENT,DELIVERY,ADDRESS from shops");
    listPane.append("\n\n\n");
    listPane.append("\tSHOP NAME" + "\t\t" + "BATCH " + "\t" + "AVAILABLE\t" + "ORDERED"+"\t" +"BILL"+ "\t" + "PAYMENT" + "\t"+"DELIVERY\t"+"\tADDRESS" + "\n");
    listPane.append("\n");
    while (rst.next()) {
    listPane.append("\t");
    listPane.append(rst.getString(1).trim());
    listPane.append("\t\t");
    listPane.append(rst.getString(2).trim());
    listPane.append("\t");
    listPane.append(rst.getString(3).trim());
    listPane.append("\t");
    listPane.append(rst.getString(4).trim());
    listPane.append("\t");
    listPane.append(rst.getString(5).trim());
    listPane.append("\t");
    listPane.append(rst.getString(6).trim());
    listPane.append("\t");
    listPane.append(rst.getString(7).trim());
    listPane.append("\t\t");
    listPane.append(rst.getString(8).trim());
    listPane.append("\n\n");
    }
    if (rst != null) {
    rst.close();
    }
    } catch (SQLException sqle) {
    JOptionPane.showMessageDialog(null, " No Records found" + sqle.getMessage());
    }
    }
    public static void main(String args[])
    {
    shops_report sr=new shops_report();
    }
    }

    ReplyDelete

Leave Comment If You Like This...Thank You..!