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!" );
}
}
}