java Excel文件导入导出

@RequestMapping(params="method=downXls")


    public voiddownXls(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException, BiffException{


  1.         //得到数据里面的内容,可以确定要导出哪些数据,要导出哪些字段,要导入什么信息


        List<Emps> empList = empService.getAllEmps();


        HSSFWorkbook wb = new HSSFWorkbook();//新建一个workBook,这里就相当于一个excel文件


        HSSFSheet sheet =wb.createSheet();//创建一个工作簿


   


//设置每列的宽度


        sheet.setColumnWidth(0, 2000);


        sheet.setColumnWidth(1, 4000);


        sheet.setColumnWidth(2, 5000);


        //字体


        HSSFFont font = workbook.createFont();


        font.setBoldweight((short)1000);


        font.setFontName("隶书");


        font.setFontHeightInPoints((short)15); //设置字体大小


        //单元格样式


        HSSFCellStyle cellStyle = workbook.createCellStyle();


         cellStyle.setFont(font);


        //给每个单元格指定样式以及内容


         HSSFCell cell0 = titleRow.createCell(0);


        cell0.setCellStyle(cellStyle);


        cell0.setCellValue(new HSSFRichTextString("职工号"));


 


        HSSFCell cell1 = titleRow.createCell(1);


        cell1.setCellStyle(cellStyle);


        cell1.setCellValue(new HSSFRichTextString("职工姓名"));


       


        HSSFCell cell2 = titleRow.createCell(2);


        cell2.setCellStyle(cellStyle);


        cell2.setCellValue(newHSSFRichTextString("部门名字"));


       


        int num = empList.size();


        for(int i = 1 ; i< num ; i++){


            HSSFRow row =sheet.createRow(i);//创建行


            row.createCell((short)0).setCellValue(newHSSFRichTextString(empList.get(i-1).getEmpId()+""));//设置没一行每个单元格的值


            row.createCell((short)1).setCellValue(newHSSFRichTextString(empList.get(i-1).getEmpName()));


            row.createCell((short)2).setCellValue(newHSSFRichTextString(empList.get(i-1).getDep().getDepName()));


        }


       


//增加一个最后一行


        HSSFRow row = sheet.createRow(num+1);


        HSSFCell footCell = row.createCell(0);


        footCell.setCellValue(new HSSFRichTextString("合计:"));


        //设置最后一行的样式


        HSSFCellStyle style = workbook.createCellStyle();


        style.setAlignment(HSSFCellStyle.ALIGN_LEFT); //内容左对齐


        footCell.setCellStyle(style);


       


        //合并单元格(第一个单元格的行数,第二个单元格的行数,第一个单元格的列,第二个单元格的列)


        sheet.addMergedRegion(newCellRangeAddress(num+1,num+1,0,2));


 


//导出成excel形式的,用流的形式下载的方式


        response.addHeader("Content-Disposition", "attachment;filename=myFile.xls");


        response.addHeader("Content-type", "application/vnd.ms-excel");


 


        try{


        OutputStream os =response.getOutputStream();


        wb.write(os);


        os.close();


        }catch(Exception e){


            e.printStackTrace();


        }


    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章