/*
* 导出
* 按照页面的条件导出
*/
@RequestMapping(params = "exportExcel")
@ResponseBody
public void exportExcel(HttpServletRequest request,HttpServletResponse response) {
//接收条件
String xm = request.getParameter("xm");
String sfzmhm = request.getParameter("sfzmhm");
String kscx = request.getParameter("kscx");
String startTime = request.getParameter("startTime") == null ? "" : request.getParameter("startTime");
String endTime = request.getParameter("endTime") == null ? "" : request.getParameter("endTime");
List list = studentService.queryAllStudentInfo(xm,sfzmhm,kscx,startTime,endTime);
studentService.export(list,startTime,endTime,request,response);
}
/*
* 导入考生
*/
@RequestMapping(params = "importExcel", method=RequestMethod.POST, produces = "text/html;charset=utf-8")
@ResponseBody
public String getPathfileName(@RequestParam("file")MultipartFile file) {
String msg = studentService.saveStudent(file);
return msg;
}
返回格式如下:
假如 数据库表:student
xm age
张三 18
李四 20
王五 50
那么List> list = POIUtil.readExcel(file, 3);
返回的数据就是
[[张三,18],[李四,20],[王五,50]]
//导出
public void export(List list, String startTime, String endTime,HttpServletRequest request,HttpServletResponse response) {
//导出文件的名字
String fileName = "考生信息.xlsx";
//第一行内容
List
/**
* 导入
*/
@Transactional
public String saveStudent(MultipartFile file) {
String msg=null;
Map map3 = new HashMap();
try {
//3:excel中第三行数据开始导入数据库
List> list = POIUtil.readExcel(file, 3);
//批量添加的list
List insertList = new ArrayList();
//批量修改的list
List updateList = new ArrayList();
for(int i =0;i0) {
if(!list.get(i).get(0).equals("总计")){
HhStudent student = new HhStudent();
student.setId(UUID.randomUUID().toString());
student.setXm(list.get(i).get(0));
student.setSfzmhm(list.get(i).get(1));
student.setYkrq(DateUtil.parse(list.get(i).get(2)));
student.setKscx(list.get(i).get(3));
if(!student.getXm().equals("")) {
HhStudentExample example = new HhStudentExample();
Criteria criteria = example.createCriteria();
criteria.andXmEqualTo(student.getXm());
criteria.andSfzmhmEqualTo(student.getSfzmhm());
criteria.andYkrqEqualTo(DateUtil.parse(list.get(i).get(2)));
List example2 = hHstudentMapper.selectByExample(example);
if(example2.size()==0) {//无重复
insertList.add(student);
if(insertList.size()>=10){
hHstudentMapper.insertStudent(insertList);
insertList.clear();
}
}else {
student.setId(example2.get(0).getId());
updateList.add(student);
if(updateList.size()>=10){
hHstudentMapper.updateStudent(updateList);
updateList.clear();
}
}
}
}
}
}
if(insertList.size()>0) {
hHstudentMapper.insertStudent(insertList);
}
if(updateList.size()>0) {
hHstudentMapper.updateStudent(updateList);
}
map3.put("code", "200");
map3.put("msg", "保存成功!");
} catch (Exception e) {
map3.put("code", "201");
map3.put("msg", "保存失败!");
}
msg= JSON.toJSONString(map3);
return msg;
}
public class POIUtil {
private static Logger logger = Logger.getLogger(POIUtil.class);
private final static String xls = "xls";
private final static String xlsx = "xlsx";
/**
* 读入excel文件,解析后返回
* @param file
* @throws IOException
*/
public static List> readExcel(MultipartFile file,int startReadRow) throws IOException{
//检查文件
checkFile(file);
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List> list = new ArrayList< List>();
//共有多少页
int sheetTotal = workbook.getNumberOfSheets();
if(workbook != null){
for(int sheetIndex = 0;sheetIndex < sheetTotal;sheetIndex++){
Sheet sheet = workbook.getSheetAt(sheetIndex);
//如果当前sheet为null,跳过
if(sheet == null){
continue;
}
//获得当前sheet的开始行索引,从0开始
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行索引
int lastRowNum = sheet.getLastRowNum();
for(int rowNum = firstRowNum+startReadRow-1;rowNum <= lastRowNum;rowNum++){
Row row = sheet.getRow(rowNum);
boolean b = isRowEmpty(row);
if (b) {
continue;
}
if(row == null){
continue;
}
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
//创建一个cellList集合,用来存放当前
List cellList = new ArrayList<>();
for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
cellList.add(getCellValue(row.getCell(i)));
}
list.add(cellList);
}
}
}
//最终返回的是一个String类型的list数组
return list;
}
public static void checkFile(MultipartFile file) throws IOException{
//判断文件是否存在
if(null == file){
//该日志生成位置可以在log4j里面配置
logger.error("文件不存在!");
throw new FileNotFoundException("文件不存在!");
}
//获得文件名
String fileName = file.getOriginalFilename();
//判断文件是否是excel文件
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
logger.error(fileName + "不是excel文件");
throw new IOException(fileName + "不是excel文件");
}
}
public static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007 及2007以上
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
logger.info(e.getMessage());
}
return workbook;
}
public static String getCellValue(Cell cell){
//将空的单元格设置为"";
String cellValue = "";
if(cell == null){
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
//判断某一行是不是为空行
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
return false;
}
return true;
}
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/*
* 导出excel
* fileName是带扩展名的全称
*/
public static Map exportXls(HttpServletRequest request,HttpServletResponse response,
String fileName,int startIndex ,int lieNum,List
这样就很清楚了吧。
导出的图如下:
导入用到的的Excel: