一、首先说说我的思路
jsp页面上传文件按扭,文件传到controller进行poi处理成我想要的数据,然后存入数据库
二、controller层
@Controller
@RequestMapping("/admin")
public class SurnameNameOriginController {
@Resource(name = "surnameNameOriginService")
private SurnameNameOriginService surnameNameOriginService;
@RequestMapping(value = "/surname_file_upload", method = RequestMethod.POST)
public String surnameFileUploadHandle(HttpServletRequest request,HttpServletResponse response,
@RequestParam(required = true, defaultValue = "1") Integer page,
@RequestParam(value="filename") MultipartFile file)throws Exception{
response.setContentType("application/vnd.ms-excel;charset=utf-8");
HttpSession session = request.getSession();
AdminUser suserInfo = (AdminUser) session.getAttribute("admin_login_info");
if (null != suserInfo) {
InputStream in = file.getInputStream();
surnameNameOriginService.excelUpload(in,file,suserInfo.getId(),suserInfo.getRealName());
in.close();
}
request.setAttribute("page", page);
return "redirect:surname_origin_list.do?page=" + page;
}
}
三、service层
public interface SurnameNameOriginService {
/**
* 通过excel导入数据
* @param in 输入流
* @param file 文件对象
* @param userId 创建者编号
* @param userName 创建者姓名
* @throws Exception
*/
public void excelUpload(InputStream in, MultipartFile file,Long userId,String userName) throws Exception ;
}
四、service实现类
@Service("surnameNameOriginService")
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={RuntimeException.class})
public class SurnameNameOriginServiceImpl implements SurnameNameOriginService{
//姓氏溯源
@Resource(name="surnameNameOriginMapper")
private SurnameNameOriginMapper surnameNameOriginMapper;
/**
* 通过excel导入数据
* @param in 输入流
* @param file 文件对象
* @param userId 创建者编号
* @param userName 创建者姓名
* @throws Exception
*/
@Override
public void excelUpload(InputStream in, MultipartFile file,Long userId,String userName) throws Exception {
//查询数据库已经存在的姓氏
List origin_list = surnameNameOriginMapper.findAllSurname();
//存取上传表格的姓氏
List excel_upload = new ArrayList();
//对excel表格进行处理
List> listob = ImportExcelUtil.getBankListByExcel(in,file.getOriginalFilename());
List originList = new ArrayList();
for (int i = 0; i < listob.size(); i++) {
List ob = listob.get(i);
excel_upload.add(String.valueOf(ob.get(0)));
}
//去除导入姓氏重复的数据
List excel_upload2 = new ArrayList(new HashSet(excel_upload));
//判断导入的姓氏是否有已经存在数据库的
Collection exists=new ArrayList(excel_upload2);
Collection notexists=new ArrayList(excel_upload2);
exists.removeAll(origin_list);
notexists.removeAll(exists);
//将存在于的姓氏全部剔除
excel_upload2.removeAll(notexists);
for(int j=0;j0){
surnameNameOriginMapper.batchSaveEntity(originList);
}
}
}
五、工具类
public class ImportExcelUtil {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* Excel导入
*/
public static List> getBankListByExcel(InputStream in, String fileName) throws Exception{
List> list = null;
//创建Excel工作薄
Workbook work = getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList>();
//遍历Excel中所有的sheet
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||row.getFirstCellNum()==j){
continue;
}
//遍历所有的列
List li = new ArrayList();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(getCellValue(cell));
}
list.add(li);
}
}
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
*/
public static Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("deprecation")
public static Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化字符类型的数字
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}else{
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
}
}
}