abdeen-ahmad
12/10/2015 - 6:09 PM

query to export JTable into Excel file

query to export JTable into Excel file

	public void actionPerformed(ActionEvent arg0) {
				try{
					JFileChooser jf = new JFileChooser();
					jf.setDialogTitle("Save Excel File");
					int result = jf.showSaveDialog(null); 
					if (result == JFileChooser.APPROVE_OPTION) {
						String excelpath = jf.getSelectedFile().getAbsolutePath();
						excelpath = excelpath.replace("\\","/");
						textField.setText(excelpath );
						ExcelExporter exp = new ExcelExporter();
						//exp.exportTable(table, new File("\""+ excelpath + "\""));
						//exp.exportTable(table, new File("C:/Users/abdee_000/Desktop/test1.xls"));
						exp.exportTable(table, new File(excelpath));
						
						
						
						//ExcelHelper eh = new ExcelHelper(excelpath);
						//ProductDAO pdao = new ProductDAO();
						
						
					}
					
				}catch(Exception e){
					e.printStackTrace();
					JOptionPane.showMessageDialog(null, e.getMessage());
				}
			}
		});
import java.io.*;
import javax.swing.table.TableModel;
import javax.swing.*;
import  java.nio.charset.StandardCharsets ;
public class ExcelExporter {
	
	ExcelExporter(){}
		public void exportTable(JTable table, File file)throws IOException{
			TableModel model = table.getModel();
			byte[] arr= file.toString().getBytes(StandardCharsets.UTF_8);
			String str2 = new String(arr);
			FileOutputStream outr= new FileOutputStream(str2);
			
			
			OutputStreamWriter y2r = new OutputStreamWriter(outr,"UTF-8");
			
			BufferedWriter bwr= new BufferedWriter(y2r);
			for(int i=0;i<model.getColumnCount();i++){
				bwr.write(model.getColumnName(i)+"\t");

				
			}
			bwr.write("\n");
			
			for(int i=0;i<model.getRowCount();i++){
				for(int j=0;j<model.getColumnCount();j++){
				bwr.write(model.getValueAt(i, j).toString()+"\t");	
				}
			bwr.write("\n");
			}
			bwr.close();
	}
}