Skip to content

Instantly share code, notes, and snippets.

@behitek
Last active December 15, 2016 16:32
Show Gist options
  • Save behitek/db4aa46b2af5b7a3023807dfaa89b28a to your computer and use it in GitHub Desktop.
Save behitek/db4aa46b2af5b7a3023807dfaa89b28a to your computer and use it in GitHub Desktop.
Read Write jTable - Excel in java swing using POI

Xuất jTable sang file Excel

Hàm thực thi đọc dữ liệu từ jTable vào file Excel

public static void toExcel(JTable table, File file) throws IOException {
        String sheetName = "Sheet1";//name of sheet
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        TableModel model = table.getModel();
        //Get colum name
        HSSFRow row = sheet.createRow(0);
        for(int i = 0;i < model.getColumnCount();i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(model.getColumnName(i).toString());
        }
        //iterating r number of rows
        for (int r = 1; r <= model.getRowCount(); r++) {
            row = sheet.createRow(r);
            //iterating c number of columns
            for (int c = 0; c < model.getColumnCount(); c++) {
                HSSFCell cell = row.createCell(c);

                cell.setCellValue(model.getValueAt(r-1, c).toString());
            }
        }

Gọi hàm trong sự kiện Button click

private void btnXuatActionPerformed(java.awt.event.ActionEvent evt) {                                        
      // TODO add your handling code here:
      JFileChooser fc = new JFileChooser();
      int option = fc.showSaveDialog(this);
      if (option == JFileChooser.APPROVE_OPTION) {
          String filename = fc.getSelectedFile().getName();
          String path = fc.getSelectedFile().getParentFile().getPath();
          int len = filename.length();
          String ext = "";
          String file = "";

          if (len > 4) {
              ext = filename.substring(len - 4, len);
          }

          if (ext.equals(".xls")) {
              file = path + "\\" + filename;
          } else {
              file = path + "\\" + filename + ".xls";
          }
          try {
              toExcel(tbNXB, new File(file));
              JOptionPane.showMessageDialog(this, "Xuất file thành công!");
          } catch (IOException ex) {
              Logger.getLogger(frmSach.class.getName()).log(Level.SEVERE, null, ex);
              JOptionPane.showMessageDialog(this, "Xuất file không thành công!");
          }
      }
  } 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment