java实体类导入Excel

来源:互联网 发布:天勤网络 编辑:程序博客网 时间:2024/06/04 20:03
if(carList.isEmpty()){//carList为实体类链表
JOptionPane.showMessageDialog(CarRent.this, "数据为空!");
}else{

    int n=1;//记录Excel行数

    int i=0;

    HSSFCell cell;
    // 第一步,创建一个webbook,对应一个Excel文件
    HSSFWorkbook wb = new HSSFWorkbook();
    // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
    HSSFSheet sheet = wb.createSheet("表一");
    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    HSSFRow row = sheet.createRow((int) 0);
    //实例化对象将属性名添加到Excel表头   CarInformation为实体类名
    CarInformation car=new CarInformation();
    Field[] fields = CarInformation.class.getDeclaredFields();
for (Field field : fields)
{
field.setAccessible(true);
String rsVal = field.getName();
cell = row.createCell(i);
cell.setCellValue(rsVal);
i++;
}
// 第四步,创建单元格,并设置值
Iterator it = carList.iterator();
     while(it.hasNext())
     {
    int m=0;
        row = sheet.createRow(n);
        CarInformation carInf = (CarInformation)it.next();
        for (Field field1 : carInf.getClass().getDeclaredFields())
{
        field1.setAccessible(true);
        try {
        row.createCell(m).setCellValue(field1.get(carInf)+"");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
        m++;
}
        n++;
     }
     //文件导出选择框
     JFileChooser jfc = new JFileChooser();
     FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel文件(*.xls)", "xls");
     jfc.setFileFilter(filter);
     int option = jfc.showSaveDialog(CarRent.this);
     if (option == JFileChooser.APPROVE_OPTION) {
         File file = jfc.getSelectedFile();
         String fname = jfc.getName(file);   //从文件名输入框中获取文件名
         //假如填写的文件名不带规定后缀名,则添上.xls后缀
         if (fname.indexOf(".xls") == -1) {
             file = new File(jfc.getCurrentDirectory(), fname + ".xls");
         }
         try {
             FileOutputStream fout = new FileOutputStream(file,true);
             wb.write(fout);
             fout.close();
         } catch (IOException e1) {
             e1.printStackTrace();
         }
     }
}
原创粉丝点击