/**
* 导入学生信息
*
* @param classid
* @param uploadFilePath
* @return
*/
public boolean uploadStudentFile(String schUuid, String classid, String uploadFilePath) {
if (StringUtils.isBlank(uploadFilePath)) {
throw new ServiceException(MessageConstants.CD50012);
}
String fileDir = globalProperty.getFileUploadPath();
// TODO
String filePath = fileDir + System.getProperty("file.separator") + uploadFilePath;
// windows
// String filePath = fileDir + "\\" + uploadFilePath;
File uploadFile = new File(filePath);

String[][] s = ExcelUtils.readExcel(uploadFile);
Map<String, Integer> numMap = new HashMap<String, Integer>();
Map<String, Integer> cardMap = new HashMap<String, Integer>();
Map<String, Integer> testNumMap = new HashMap<String, Integer>();
List<Student> students = new ArrayList<Student>();

if (s == null || s.length < 1 || !"学生姓名".equals(s[0][0]) || !"学号".equals(s[0][1]) || !"考号".equals(s[0][2])
|| !"身份证".equals(s[0][3])) {
throw new ServiceException(MessageConstants.CD50001);
}

// if (s == null || s.length < 1 || !s[0][0].equals("学生姓名")
// || !s[0][1].equals("学号") || !s[0][2].equals("考号")
// || !s[0][3].equals("身份证")) {
// throw new ServiceException(MessageConstants.CD50001);
// }
Integer fag = 0;// 判断模板数据为空
for (int i = 1; i < s.length; i++) {
if (!((s[i][0] == null || "".equals(s[i][0])) && (s[i][1] == null || "".equals(s[i][1]))
&& (s[i][2] == null || "".equals(s[i][2])) && (s[i][3] == null || "".equals(s[i][3])))) {
fag++;
Student student = new Student();
// 学生姓名
if (s[i][0] == null || "".equals(s[i][0]) || s[i][0].length() > 30) {
throw new ServiceException(MessageConstants.CD50002, new String[] { String.valueOf(i), "学生姓名" });
} else {
student.setStuName(s[i][0]);
// 学生姓名拼音
student.setPinyinAll(PinyinHelper.convertToPinyinString(s[i][0], "", PinyinFormat.WITHOUT_TONE));
// 学生姓名拼音首字母
student.setPinyinFirst(PinyinHelper.getShortPinyin(s[i][0]).substring(0, 1).toUpperCase());
}
// 学号
if (s[i][1] == null || "".equals(s[i][1]) || s[i][1].length() > 20) {
throw new ServiceException(MessageConstants.CD50002, new String[] { String.valueOf(i), "学号" });
} else {
if (!numMap.containsKey(s[i][1])) {
numMap.put(s[i][1], i);
student.setStuNum(s[i][1]);
Map<String, Object> params = Maps.newHashMap();
params.put("stuNum", s[i][1]);
// params.put("schYear", Integer.valueOf(DateUtils.getCurrentYear()));

if (studentMyBatisDao.selectStudentClassInfo(params) > 0) {
throw new ServiceException(MessageConstants.CD50007, new String[] { s[i][1],
String.valueOf(i) });
}
} else {
throw new ServiceException(MessageConstants.CD50005, new String[] { s[i][1],
String.valueOf(numMap.get(s[i][1])), String.valueOf(i) });
}
}
// 考号
if (s[i][2] != null && s[i][2].length() > 20) {
throw new ServiceException(MessageConstants.CD50002, new String[] { String.valueOf(i), "考号" });
} else {
if (!"".equals(s[i][2])) {
if (!testNumMap.containsKey(s[i][2])) {
testNumMap.put(s[i][2], i);
student.setStuTestNum(s[i][2]);
Map<String, String> map = Maps.newHashMap();
map.put("testNum", s[i][2]);
if (studentMyBatisDao.selectStuCntByTestNum(map) > 0) {
throw new ServiceException(MessageConstants.CD50008, new String[] { s[i][2],
String.valueOf(i) });
}
} else {
throw new ServiceException(MessageConstants.CD50009, new String[] { s[i][2],
String.valueOf(testNumMap.get(s[i][2])), String.valueOf(i) });
}
}
}
// 身份证号
if (s[i][3] != null && !"".equals(s[i][3])) {
if (s[i][3].length() > 18) {
throw new ServiceException(MessageConstants.CD50002, new String[] { String.valueOf(i), "身份证号" });
} else {
if (!cardMap.containsKey(s[i][3])) {
cardMap.put(s[i][3], i);
student.setStuCardid(s[i][3]);
} else {
throw new ServiceException(MessageConstants.CD50006, new String[] { s[i][3],
String.valueOf(cardMap.get(s[i][3])), String.valueOf(i) });
}
if (studentMyBatisDao.selectStuCntByCard(s[i][3]) > 0) {
throw new ServiceException(MessageConstants.CD50010, new String[] { s[i][3],
String.valueOf(i) });
}
}
}
/*
* if(s[i][3] != null && !"".equals(s[i][3]) && studentService.queryStudentCountByCard(s[i][3]) > 0) {
* addActionError(MessageConstants.E00008, new String[] { s[i][3], String.valueOf(i) }); }
*/
students.add(student);
}
}
if (fag == 0) {
throw new ServiceException(MessageConstants.CD50011);
}

// 数据验证通过
for (Student stu : students) {
// 学生表已存在此学生记录
Class cla = classJpaDao.findOne(classid);
Student dbStu = studentJpaDao.findByStuNum(stu.getStuNum());
if (null != dbStu) {
/*
* ClassstudentDto cs = new ClassstudentDto(); cs.setClassid(classId);
* cs.setStuid(studentManagerDao.queryStudentByNum (stu.getStuNum()).getStuid());
* classStudentDao.insertClassstudent(cs);
*/
Classstudent classstudent = new Classstudent();
classstudent.setClassid(classid);
classstudent.setStuid(dbStu.getGuuid());
classstudent.setSchcode(cla.getSchcode());
classstudent.setSchyear(cla.getSchyear());
classstudent.setStuid(cla.getSchoolid());
classstudent.setSchZoneCode(cla.getSchcode());
classstudent.setClassid(cla.getClassname());
classstudent.setGrade(cla.getGrade());
classstudent.setArts(cla.getArts());
classstudentJpaDao.save(classstudent);
} else {
// 学生表不存在此记录
String stuId = commonService.getSequence(Constants.SEQ_T_STUDENT, 8);
stu.setGuuid(stuId);
stu.setSchcode(cla.getSchcode());
studentMyBatisDao.insertStudent(stu);

Classstudent classstudent = new Classstudent();
classstudent.setClassid(classid);
classstudent.setStuid(stuId);
classstudent.setSchcode(cla.getSchcode());
classstudent.setSchyear(cla.getSchyear());
classstudent.setSchZoneCode(cla.getSchcode());
classstudent.setClassname(cla.getClassname());
classstudent.setGrade(cla.getGrade());
classstudent.setArts(cla.getArts());
classstudent.setSchoolid(schUuid);
classstudentJpaDao.save(classstudent);

}
}

return true;
}

//-------------------------------------------------我是分隔线--------------------------------------------------

模板导出

/**
* 学生模板导出
*/
public ExamStatistVo DownloadStudent(String classId, String schoolUuid, Integer grade) {
System.gc();
// 参数
Map<String, Object> map = Maps.newHashMap();
map.put("classId", classId);
List<Student> list=studentMyBatisDao.selectStudentDownload(map);
for(Student entity:list){
if(entity.getGrade()!=null){
entity.setGradeShow(Grade.GradeName(entity.getGrade()));
}
}
String fileName=list.get(0).getClassName();
// 文件模板路径
// String templateFileName = globalProperty.getTemplateFilePath() + File.separator
// + "STUDENT.xls";
// 生成路径
String resultFileName = globalProperty.getFileUploadPath() + File.separator + "stu_Download"
+ File.separator + "STUDENT.xls";
//检查路径
checkFileDirExist(globalProperty.getFileUploadPath() + File.separator + "stu_Download");
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("学生信息表-1");

Row row = sheet.createRow(0);
row.setHeight((short) (25 * 20));
Cell cell = row.createCell(0);
cell.setCellStyle(getTitleStyle(wb));
cell.setCellValue("学生姓名");

cell = row.createCell(1);
cell.setCellValue("学号");
cell.setCellStyle(getTitleStyle(wb));

cell = row.createCell(2);
cell.setCellValue("身份证");
cell.setCellStyle(getTitleStyle(wb));

// cell = row.createCell(3);
// cell.setCellValue("年级");
// cell.setCellStyle(getTitleStyle(wb));

// cell = row.createCell(4);
// cell.setCellValue("班级名称");
// cell.setCellStyle(getTitleStyle(wb));

for(int i=0;i<list.size();i++){
row = sheet.createRow(i+1);
row.setHeight((short) (25 * 10));
cell = row.createCell(0);
cell.setCellValue(list.get(i).getStuName());
// cell.setCellStyle(getValueStyle(wb));

cell = row.createCell(1);
cell.setCellValue(list.get(i).getStuNum());

// cell.setCellStyle(getValueStyle(wb));

cell = row.createCell(2);
cell.setCellValue(list.get(i).getStuCardid());
// cell.setCellStyle(getValueStyle(wb));

// cell = row.createCell(3);
// cell.setCellValue(list.get(i).getGradeShow());
// cell.setCellStyle(getValueStyle(wb));

// cell = row.createCell(4);
// cell.setCellValue(list.get(i).getClassName());
// cell.setCellStyle(getValueStyle(wb));
}
sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(2);
sheet.autoSizeColumn(3);
sheet.autoSizeColumn(4);

FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(resultFileName);
wb.write(fileOut);

} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("学生信息导出关闭异常 ");
}
}

ExamStatistVo examStatistVo = new ExamStatistVo();
examStatistVo.setPath(resultFileName);
examStatistVo.setResultFileName(fileName+".xls");
return examStatistVo;

}
/**
* 设置模板文件的输入项表格样式
* @param wb
* @return
*/
private static CellStyle getValueStyle(Workbook wb){
CellStyle style = wb.createCellStyle();
//对齐方式设置
style.setAlignment(CellStyle.ALIGN_LEFT);
//边框颜色和宽度设置
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BROWN.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BROWN.getIndex());
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BROWN.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BROWN.getIndex());
return style;
}
/**
* 设置模板文件的横向表头单元格的样式
* @param wb
* @return
*/
private static CellStyle getTitleStyle(Workbook wb){
CellStyle style = wb.createCellStyle();
//对齐方式设置
style.setAlignment(CellStyle.ALIGN_CENTER);
//边框颜色和宽度设置
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
style.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
//设置背景颜色
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
//粗体字设置
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
return style;
}
// public void createExcel(String templateFileName, Map<String, Object> map, String resultFileName) {
// try {
// // 创建XLSTransformer对象
// XLSTransformer transformer = new XLSTransformer();
// // 生成Excel文件
// transformer.transformXLS(templateFileName, map, resultFileName);
// } catch (Exception e) {
// throw new RuntimeException("error happens...", e);
// }
// }

private void checkFileDirExist(String filePath) {// 判断路径是否存在
File fp = new File(filePath);
// 创建目录
if (!fp.exists()) {
fp.mkdirs();// 目录不存在的情况下,创建目录。
}
}

//-----------------------------------------controller 页面读取 ------------------------------------------

/**
* 导出学生信息
*/
@RequestMapping(value = "/studentDownload")
public ResponseEntity<byte[]> KSXL004Download(HttpServletRequest request) throws IOException,
ServletRequestBindingException {

String classId = ServletRequestUtils.getStringParameter(request, "classId");
String schoolUuid = ServletRequestUtils.getStringParameter(request, "schoolUuid");
Integer grade = ServletRequestUtils.getIntParameter(request, "grade");

ExamStatistVo examStatistVo = stuCom.getStudentDownload(classId,schoolUuid,grade);

String resultFileName = examStatistVo.getResultFileName();
//文件路径
String filePath =examStatistVo.getPath();

File file = new File(filePath);
HttpHeaders headers = new HttpHeaders();
//重新命名
String fileName = this.getFileName(request,resultFileName);
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}

/**
* 下载文件中文名
* @param request
* @param sourceFileName
* @return
* @throws IOException
*/
private String getFileName(HttpServletRequest request,String sourceFileName) throws IOException{
String filename = null;
//判断是否是IE11
Boolean flag= request.getHeader("User-Agent").indexOf("like Gecko")>0;
//IE11 User-Agent字符串:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
//IE6~IE10版本的User-Agent字符串:Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.0; Trident/6.0)
if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") >0||flag){
filename = URLEncoder.encode(sourceFileName, "UTF-8");//IE浏览器
}else {
//转换编码格式为utf-8,保证不出现乱码,
//这个文件名称用于浏览器的下载框中自动显示的文件名
filename = new String(sourceFileName.getBytes("UTF-8"), "iso8859-1");
//firefox浏览器
//firefox浏览器User-Agent字符串:
//Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
}
return filename;
}

poi管道流的导入导出的更多相关文章

  1. poi实现excel的导入导出功能

    Java使用poi实现excel的导入导出功能: 工具类ExcelUtil,用于解析和初始化excel的数据:代码如下 package com.raycloud.kmmp.item.service.u ...

  2. 一个基于POI的通用excel导入导出工具类的简单实现及使用方法

    前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...

  3. SSM中使用POI实现excel的导入导出

    环境:导入POI对应的包 环境: Spring+SpringMVC+Mybatis POI对应的包 <dependency> <groupId>org.apache.poi&l ...

  4. Java集成POI进行Excele的导入导出,以及报错: java.lang.AbstractMethodError..........

    报错信息如下 java.lang.AbstractMethodError: org.apache.poi.xssf.usermodel.XSSFCell.setCellType(Lorg/apache ...

  5. 用poi框架进行批量导入导出实例

    Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能.我们这里使用poi对数据库中的数据进行批量导出,以及 ...

  6. 使用Poi对EXCLE的导入导出

    import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import ...

  7. POI实现excel的导入导出

    引入依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</arti ...

  8. Java利用POI导入导出Excel中的数据

         首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...

  9. 基于POI的Excel导入导出(JAVA实现)

    今天做了个excel的导入导出功能,在这记录下. 首先现在相关poi的相关jar包,资源链接:http://download.csdn.net/detail/opening_world/9663247 ...

随机推荐

  1. Hadoop 2.6.4单节点集群配置

    1.安装配置步骤 # wget http://download.oracle.com/otn-pub/java/jdk/8u91-b14/jdk-8u91-linux-x64.rpm # rpm -i ...

  2. 推荐csdn里的几篇activiti基础入门及提高的博客

    昨天有个网友加qq询问我有没有非maven搭建的activiti项目的demo,因为我博客中写了一个用maven,我当时没有,于是晚上回家尝试了一下,结果比较容易就实现了. 之后和那个网友聊了一下,他 ...

  3. My Package

    一.新建一文件夹,名称为MyBase,存放Java的基本类. 二.在MyBase包中创建基本类Base.java. package MyBase; public class Base { public ...

  4. 51nod 1290 Counting Diff Pairs 莫队 + bit

    一个长度为N的正整数数组A,给出一个数K以及Q个查询,每个查询包含2个数l和r,对于每个查询输出从A[i]到A[j]中,有多少对数,abs(A[i] - A[j]) <= K(abs表示绝对值) ...

  5. jmf找不到摄像头设备解决办法

    1.安装的jdk需要时32位的. 2.在jmfregistry中注册捕获设备. 3.jar文件必须和配置文件在一起.可以新建User library把jar文件添加进去.

  6. C Primer Plus(第五版)12

    第 12 章 存储类, 链接和内存管理 在本章中你将学习下列内容 . 关键字: auto, extern, static, register, const, volatile, restricted. ...

  7. gcc与makefile编译 BY 四喜三顺

    gcc编译控制过程:(假设源代码为a.c)(1)源文件到预处理文件:    gcc -E -o a.cxx a.c    a.cxx显示调用哪些头文件(2)生成汇编代码:              g ...

  8. Archlinux添加MP3播放器

    方法1: # pacman -S mplayer From: http://www.linuxdiyf.com/viewarticle.php?id=89207 用mplayer循环播放音乐:mpla ...

  9. Spring MVC入门知识总结

    2.1.Spring Web MVC是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职 ...

  10. node js 调试

    npm install -g node-inspector node --debug app.js >重新打开一个窗口   node-inspector &   KO!       no ...