1

Anyone have an idea how to insert data to existing excel file from jtable am using java to develop this program and my scenario is like this, jtable data insert to excel but the excel already have a design and formula. I don't know how to start it so I ask question. thank you for your tip.

2 Answers 2

2

Excel uses a complicated formatting for its native .xls files but it also supports other formats. I am using the Tab-Separated Values (TSV), which is commonly used for transferring information from a database program to a spreadsheet.

You can use below code to extract data from Jtable and export it to excel.

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

First you need to extract data from JTable. You this method:

public Object[][] getTableData (JTable table) {
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
    Object[][] tableData = new Object[nRow][nCol];
    for (int i = 0 ; i < nRow ; i++)
        for (int j = 0 ; j < nCol ; j++)
            tableData[i][j] = dtm.getValueAt(i,j);
    return tableData;
}

Now having data you can append them into excel file using apache poi. Here are tutorials http://poi.apache.org/spreadsheet/quick-guide.html

1 Comment

am going to insert the data to exciting excel file?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.