需要的jar包
org.apache.poi poi 3.14 org.apache.poi poi-ooxml-schemas 3.14 org.apache.poi poi-ooxml 3.14 org.apache.httpcomponents httpclient 4.5.2
工具类
public class ExcelUtil { private final static String excel2003L =".xls"; //2003- 版本的excel private final static String excel2007U =".xlsx"; //2007+ 版本的excel /** * 描述:获取IO流中的数据,组装成List
>对象 * @param in,fileName * @return * @throws */ public List
> getBankListByExcel(InputStream in,String fileName) throws Exception{ List
> list = null; //创建Excel工作薄 Workbook work = this.getWorkbook(in,fileName); if(null == work){ throw new Exception("创建Excel工作薄为空!"); } Sheet sheet = null; //页数 Row row = null; //行数 Cell cell = null; //列数 list = new ArrayList
>(); //遍历Excel中所有的sheet // 将最大的列数记录下来 int lastCellNum = 0; for (int i = 0; i < work.getNumberOfSheets(); i++) { sheet = work.getSheetAt(i); if(sheet==null){continue;} //遍历当前sheet中的所有行 for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) { row = sheet.getRow(j); if(row==null){continue;} //遍历所有的列 List
service接口
public interface ExcelService { /** * 导入excel * @param file excel文件 * @return 0表示失败,1表示成功 * @throws Exception */ String ajaxUploadExcel(MultipartFile file) throws Exception; /** * 导入excel * @return * @throws Exception */ XSSFWorkbook exportExcelInfo() throws Exception; }
service实现类
@Service public class ExcelServiceImpl implements ExcelService { @Autowired private UserDao dao; @Autowired private UserService service; protected static Logger logger = LoggerFactory.getLogger(ExcelServiceImpl.class); public String ajaxUploadExcel(MultipartFile file) throws Exception { if(file.isEmpty()){ try { throw new Exception("文件不存在!"); } catch (Exception e) { logger.debug(e.getMessage()); } } InputStream in =null; try { in = file.getInputStream(); } catch (IOException e) { logger.debug(e.getMessage()); } List
> listob = null; try { //将文件中的数据转换成一个list集合 listob = new ExcelUtil().getBankListByExcel(in,file.getOriginalFilename()); } catch (Exception e) { logger.debug(e.getMessage()); } //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出 for (int i = 0; i < listob.size(); i++) { User userExcel = new User(); /* 设置值之前可以进行验证哪些字段是不能再添加的 */ if (StringUtils.isEmpty(String.valueOf(listob.get(i).get(1))) || StringUtils.isEmpty(String.valueOf(listob.get(i).get(0))) || StringUtils.isEmpty(String.valueOf(listob.get(i).get(3)))){ throw new Exception("基本信息不能为空"); } if (service.validateUseridcard(String.valueOf(listob.get(i).get(1)))){ throw new Exception("身份证号码不能一致"); } userExcel.setName(String.valueOf(listob.get(i).get(0))); // 表格的第一列 注意数据格式需要对应实体类属性 userExcel.setIdcard(String.valueOf(listob.get(i).get(1))); // 表格的第二列 userExcel.setMobiile(java.lang.String.valueOf(listob.get(i).get(2))); // 表格的第三列 userExcel.setAddress(String.valueOf(listob.get(i).get(3))); // 表格的第四列 userExcel.setAge(String.valueOf(listob.get(i).get(4))); // 表格的第五列 //由于数据库中此字段是datetime,所以要将字符串时间格式:yyyy-MM-dd HH:mm,转为Date类型 if (!StringUtils.isEmpty(listob.get(i).get(5))) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); userExcel.setBirtday(sdf.parse(String.valueOf(listob.get(i).get(5)))); // 表格的第六列 }else { userExcel.setBirtday(new Date()); } logger.info("读取的对象是:"+userExcel); //进行数据保存 dao.saveUser(userExcel); } logger.info("文件导入成功!"); return "1"; } public XSSFWorkbook exportExcelInfo() throws Exception { List
实体类
public class ExcelBean implements Serializable { private String headTextName; //列头(标题)名 private String propertyName; //对应字段名 private Integer cols; //合并单元格数 private XSSFCellStyle cellStyle; public ExcelBean(String headTextName, String propertyName, Integer cols, XSSFCellStyle cellStyle) { this.headTextName = headTextName; this.propertyName = propertyName; this.cols = cols; this.cellStyle = cellStyle; } public ExcelBean(String headTextName, String propertyName, Integer cols) { this.headTextName = headTextName; this.propertyName = propertyName; this.cols = cols; } public ExcelBean() { } public String getHeadTextName() { return headTextName; } public void setHeadTextName(String headTextName) { this.headTextName = headTextName; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public Integer getCols() { return cols; } public void setCols(Integer cols) { this.cols = cols; } public XSSFCellStyle getCellStyle() { return cellStyle; } public void setCellStyle(XSSFCellStyle cellStyle) { this.cellStyle = cellStyle; } }
@RequestMapping(value="ajaxUpload", produces = "application/text; charset=utf-8",method = RequestMethod.POST)
@ResponseBody
public String UploadExcel(@RequestParam(value = "upfile",required = false) MultipartFile file){
String msg = null;
try {
msg = excelService.ajaxUploadExcel(file);
return msg;
} catch (Exception e) {
System.err.println(e.getMessage());
logger.debug(e.getMessage());
}
return "0";
}
@RequestMapping(value = "downloadExcel",method = RequestMethod.POST)
public void downloadExcel(HttpServletRequest request,HttpServletResponse response){
//导出Excel对象
XSSFWorkbook workbook = null;
OutputStream output = null;
BufferedOutputStream bufferedOutput = null;
try {
response.reset(); //清除buffer缓存
//Map map=new HashMap();
// 指定下载的文件名
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+new String("用户表.xlsx".getBytes(),"iso-8859-1"));
//将查到的数据用XSSFWorkbook保存并创建一个流
workbook = excelService.exportExcelInfo();
output = response.getOutputStream();
bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.flush();
//最后通过流写进去
workbook.write(bufferedOutput);
} catch (Exception e) {
System.err.println(e.getMessage());
logger.debug(e.getMessage());
}finally {
try {
bufferedOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
html
jquery
$("#importExcel").on("click",function (){ var formData = new FormData() //检验导入的文件是否为Excel文件 var uploadFile = $('#upfile').val() formData.append("upfile",$("#upfile")[0].files[0]) formData.append("name",uploadFile) if(uploadFile == null || uploadFile == ''){ alert("请选择要上传的Excel文件") return false; }else{ var fileExtend = uploadFile.substring(uploadFile.lastIndexOf('.')).toLowerCase(); if(fileExtend == '.xls' || fileExtend == '.xlsx'){ $.ajax({ url:"ajaxUpload", type:"POST", data:formData, processData:false, contentType:false, success:function (data) { if (data == '1'){ alert("导入成功") }else{ alert("导入失败,日志有错误信息") } } }) return true }else{ alert("文件格式需为.xls格式或者.xlsx格式"); return false } } }) $("#downloadExcel").on("click",function (){ //弹出对话框 var result = confirm("是否导出Excel?") if (result) { $.post('downloadExcel')//直接发出请求不需要参数啥的 } })