• Excel导入/导出


    1、依赖jar包

    jxl.jar
    2、导入
    1. publicstaticvoid main(String[] args){
    2. /**Excel文件转JavaBean**/
    3. List<StuEntity> listExcel=StuService.getAllByExcel("d://book.xls");
    4. //保存到数据库
    5. ...
    6. }
     
    1. publicstaticList<StuEntity> getAllByExcel(String file){
    2. List<StuEntity> list=newArrayList<StuEntity>();
    3. try{
    4. /**Excel文件转工作薄**/
    5. Workbook rwb=Workbook.getWorkbook(newFile(file));
    6. Sheet rs=rwb.getSheet("Test Shee 1");//获取表
    7. int clos=rs.getColumns();//获取列
    8. int rows=rs.getRows();//获取行
    9. /**工作薄转JavaBean**/
    10. for(int i =1; i < rows; i++){
    11. for(int j =0; j < clos; j++){
    12. String id=rs.getCell(j++, i).getContents();//获取单元格
    13. String name=rs.getCell(j++, i).getContents();
    14. String sex=rs.getCell(j++, i).getContents();
    15. String num=rs.getCell(j++, i).getContents();
    16. list.add(newStuEntity(Integer.parseInt(id), name, sex,Integer.parseInt(num)));
    17. }
    18. }
    19. }catch(Exception e){
    20. e.printStackTrace();
    21. }
    22. return list;
    23. }
    3、导出
    1. publicstaticvoid main(String[] args){
    2. try{
    3.            /**JavaBean**/
    4. List<StuEntity> list=StuService.getAllByDb();
    5. Label labelId=newLabel(0,0,"编号(id)");//表示第
    6. Label labelName=newLabel(1,0,"姓名(name)");
    7. Label labelSex=newLabel(2,0,"性别(sex)");
    8. Label labelNum=newLabel(3,0,"薪水(num)");
    9. /**创建Excel文件**/
    10. String fileName ="D://book.xls";
    11. File file=newFile(fileName);
    12. if(!file.exists()){
    13. file.createNewFile();
    14. }
    15. /**Excel文件转工作薄**/
    16. WritableWorkbook wwb =Workbook.createWorkbook(file);
    17. /**创建表**/
    18. WritableSheet ws = wwb.createSheet("Test Shee 1",0);
    19. ws.addCell(labelId);//添加单元格
    20. ws.addCell(labelName);
    21. ws.addCell(labelSex);
    22. ws.addCell(labelNum);
    23. for(int i =0; i < list.size(); i++){
    24. Label labelId_i=newLabel(0, i+1, list.get(i).getId()+"");
    25. Label labelName_i=newLabel(1, i+1, list.get(i).getName());
    26. Label labelSex_i=newLabel(2, i+1, list.get(i).getSex());
    27. Label labelNum_i=newLabel(3, i+1, list.get(i).getNum()+"");
    28. ws.addCell(labelId_i);
    29. ws.addCell(labelName_i);
    30. ws.addCell(labelSex_i);
    31. ws.addCell(labelNum_i);
    32. }
    33. //写进文档
    34. wwb.write();
    35. // 关闭Excel工作簿对象
    36. wwb.close();
    37. }catch(Exception e){
    38. // TODO Auto-generated catch block
    39. e.printStackTrace();
    40. }
    41. }
     
     





  • 相关阅读:
    shell cut
    查询表名
    RandomAccessFile
    eclipse 背景颜色
    JAVA 获取分行符
    date time insert
    shell date time
    python
    gdg shell
    shell入门之变量测试
  • 原文地址:https://www.cnblogs.com/RocketMan/p/6428380.html
Copyright © 2020-2023  润新知