一、导入maven依赖包
< dependency> < groupId> org.apache.poi< / groupId> < artifactId> poi- ooxml- schemas< / artifactId> < version> 4.1 .2 < / version> < / dependency> < dependency> < groupId> org.apache.poi< / groupId> < artifactId> poi< / artifactId> < version> 4.1 .2 < / version> < / dependency>
二、案例代码
public void exportExcel ( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HSSFWorkbook workbook = new HSSFWorkbook ( ) ; HSSFSheet sheet = workbook. createSheet ( "员工表一" ) ; HSSFRow row = sheet. createRow ( 0 ) ; HSSFCell cell = row. createCell ( 0 ) ; cell. setCellValue ( "员工工号" ) ; cell = row. createCell ( 1 ) ; cell. setCellValue ( "省份证号" ) ; cell = row. createCell ( 2 ) ; cell. setCellValue ( "姓名" ) ; cell = row. createCell ( 3 ) ; cell. setCellValue ( "性别" ) ; cell = row. createCell ( 4 ) ; cell. setCellValue ( "出生日期" ) ; cell = row. createCell ( 5 ) ; cell. setCellValue ( "联系方式" ) ; cell = row. createCell ( 6 ) ; cell. setCellValue ( "家庭地址" ) ; cell = row. createCell ( 7 ) ; cell. setCellValue ( "担任职务" ) ; cell = row. createCell ( 8 ) ; cell. setCellValue ( "角色名称" ) ; cell = row. createCell ( 9 ) ; cell. setCellValue ( "所属科室" ) ; List< Doctor> list = doctorService. findAll ( ) ; SimpleDateFormat simpleDateFormat = new SimpleDateFormat ( "YYYY-MM-dd" ) ; for ( int i = 0 ; i < list. size ( ) ; i++ ) { HSSFRow row1 = sheet. createRow ( i + 1 ) ; Doctor doctor = list. get ( i) ; row1. createCell ( 0 ) . setCellValue ( doctor. getDocid ( ) ) ; row1. createCell ( 1 ) . setCellValue ( doctor. getIdcard ( ) ) ; row1. createCell ( 2 ) . setCellValue ( doctor. getDocname ( ) ) ; row1. createCell ( 3 ) . setCellValue ( doctor. getDocsex ( ) ) ; row1. createCell ( 4 ) . setCellValue ( simpleDateFormat. format ( doctor. getDocbirthday ( ) ) ) ; row1. createCell ( 5 ) . setCellValue ( doctor. getDocphone ( ) ) ; row1. createCell ( 6 ) . setCellValue ( doctor. getDocaddress ( ) ) ; row1. createCell ( 7 ) . setCellValue ( doctor. getDuty ( ) ) ; row1. createCell ( 8 ) . setCellValue ( doctor. getRolename ( ) ) ; row1. createCell ( 9 ) . setCellValue ( doctor. getDptname ( ) ) ; } File file = new File ( "E://hospital//doctor.xls" ) ; if ( file. exists ( ) ) { file. delete ( ) ; } try { file. createNewFile ( ) ; workbook. write ( file) ; System. out. println ( "导出到成功" ) ; System. out. println ( "默认位置:E://hospital//doctor.xls" ) ; workbook. close ( ) ; } catch ( IOException e) { e. printStackTrace ( ) ; } request. setAttribute ( "msg" , "导出成功--已保存到:E://hospital//doctor.xls" ) ; request. getRequestDispatcher ( "/success.jsp" ) . forward ( request, response) ; }
三、运行截图