开发者社区 问答 正文

Java读取Excel文档再根据条件输出到txt里

读取个Excel文档,再根据条件输出到txt里,怎么控制输出格式呢?

展开
收起
蛮大人123 2016-02-26 15:04:26 3507 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    用poi吧,先读取excel表格数据,然后再写入到txt里面;
    给你个案例你看看

    public class CreateExcel {
     private static List getstudent() throws Exception{
     List list=new ArrayList();
     SimpleDateFormat df=new SimpleDateFormat("yyyy-mm-dd");
     Student stu=new Student(13, "张三", 14, df.parse("2015-3-3"));
     Student stu1=new Student(17, "张三", 18, df.parse("2015-3-4"));
     Student stu2=new Student(23, "张三", 21, df.parse("2015-3-5"));
     list.add(stu);
     list.add(stu1);
     list.add(stu2);
     return list;
    
     }
     public static void main(String[] args) {
     //第一步,创建一个webbook,对应一个excel文件
    HSSFWorkbook wb=new HSSFWorkbook();
     //第二步,在webbook中添加一个sheet,对应excel文件中的sheet
     HSSFSheet sheet=wb.createSheet("学生表一");
     //第三步,在sheet中添加表头第0行
    HSSFRow row=sheet.createRow((int)0);
     //第四步,创建单元格,并设置表头 设置表头居中
    HSSFCellStyle style=wb.createCellStyle();
     style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中表格
    HSSFCell cell=row.createCell((short)0);
     cell.setCellValue("学号");
    cell.setCellStyle(style);
     cell=row.createCell((short)1);
     cell.setCellValue("姓名");
    
    cell.setCellStyle(style);
    
     cell = row.createCell((short) 2);
    
     cell.setCellValue("年龄");
    
    cell.setCellStyle(style);
    
     cell = row.createCell((short) 3);
    
     cell.setCellValue("生日");
    
    cell.setCellStyle(style);
     //第五步,写入实体数据
    try {
     List list=CreateExcel.getstudent();
     for(int i=0;i<list.size();i++){
     row=sheet.createRow((int)i+1);
     Student str=(Student) list.get(i);
     //第六步创建单元格,并设置值
    row.createCell(0).setCellValue(str.getId());
     row.createCell(1).setCellValue(str.getName());
     row.createCell(2).setCellValue(str.getAge());
     row.createCell(3).setCellValue(new SimpleDateFormat("yyy-mm-dd").format(str.getBirth()));
     }
     //第七步将文件存到指定位置
    FileOutputStream fout=new FileOutputStream("D:/student.txt");
     wb.write(fout);
     fout.close();
     } catch (Exception e) {
     e.printStackTrace();
     }
     }
    }
    2019-07-17 18:48:17
    赞同 展开评论
问答分类:
问答地址: