一、文件异步上传
传统表单提交文件上传会刷新页面,使用OCUpload插件可以实现异步上传。
(1)页面部分
(2)Action
@Controller @Scope("prototype") public class RegionAction extends BaseAction<Region>{ @Autowired private RegionService regionService; private File myFile; private String myFileFileName; public String importExcel() throws IOException{ if(myFile != null){ //是否是Excel if(myFileFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){ String flag = "1"; try{ regionService.importExcel(myFile,myFileFileName); }catch(Exception e){ e.printStackTrace(); flag = "0"; } ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8"); ServletActionContext.getResponse().getWriter().print(flag); } } return NONE; } public void setMyFile(File myFile){ this.myFile = myFile; } public String getMyFileFileName(){ return myFileFileName; } public void setMyFileFileName(String myFileFileName){ this.myFileFileName = myFileFileName; } }
(3)POI读取Excel
@Service @Transactional public class RegionServiceImpl implements RegionService{ @Autowired private RegionDao regionDao; @Override public void importExcel(File myFile,String fileName) throws Exception{ List<Region> list = new ArrayList<Region>(); boolean is03Excel = fileName.matches("^.+\\.(?i)(xls)$"); FileInputStream inputStream = new FileInputStream(myFile); // 1、读取工作簿 Workbook workbook = is03Excel ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream); // 2、读取第一个工作表 Sheet sheet = workbook.getSheetAt(0); // 遍历获取每行 for(Row row : sheet){ // 获取行号 int num = row.getRowNum(); // 第一行不保存到数据库 if(num != 0){ row.getCell(0).setCellType(Cell.CELL_TYPE_STRING); row.getCell(1).setCellType(Cell.CELL_TYPE_STRING); row.getCell(2).setCellType(Cell.CELL_TYPE_STRING); row.getCell(3).setCellType(Cell.CELL_TYPE_STRING); row.getCell(4).setCellType(Cell.CELL_TYPE_STRING); // 获取省市县 String id = row.getCell(0).getStringCellValue(); String province = row.getCell(1).getStringCellValue(); String city = row.getCell(2).getStringCellValue(); String district = row.getCell(3).getStringCellValue(); String postcode = row.getCell(4).getStringCellValue(); Region region = new Region(id,province,city,district,postcode,null,null,null); list.add(region); } } regionDao.saveBatch(list); } }
@Repository public class RegionDaoImpl extends BaseDaoImpl<Region> implements RegionDao{ @Override public void saveBatch(List<Region> list){ for(Region region : list){ saveOrUpdate(region); } } }
时间: 2024-10-11 08:03:33