poi管道流的导入导出
/**
* 导入学生信息
*
* @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管道流的导入导出的更多相关文章
- poi实现excel的导入导出功能
Java使用poi实现excel的导入导出功能: 工具类ExcelUtil,用于解析和初始化excel的数据:代码如下 package com.raycloud.kmmp.item.service.u ...
- 一个基于POI的通用excel导入导出工具类的简单实现及使用方法
前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...
- SSM中使用POI实现excel的导入导出
环境:导入POI对应的包 环境: Spring+SpringMVC+Mybatis POI对应的包 <dependency> <groupId>org.apache.poi&l ...
- Java集成POI进行Excele的导入导出,以及报错: java.lang.AbstractMethodError..........
报错信息如下 java.lang.AbstractMethodError: org.apache.poi.xssf.usermodel.XSSFCell.setCellType(Lorg/apache ...
- 用poi框架进行批量导入导出实例
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能.我们这里使用poi对数据库中的数据进行批量导出,以及 ...
- 使用Poi对EXCLE的导入导出
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import ...
- POI实现excel的导入导出
引入依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</arti ...
- Java利用POI导入导出Excel中的数据
首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...
- 基于POI的Excel导入导出(JAVA实现)
今天做了个excel的导入导出功能,在这记录下. 首先现在相关poi的相关jar包,资源链接:http://download.csdn.net/detail/opening_world/9663247 ...
随机推荐
- 【freemaker】之判断是否为空,表达式的使用
测试代码 @Test public void test05(){ try { freemakerUtil.fprint(root, "05.ftl",fn+"05.htm ...
- javascript性能优化总结一(转载人家)
一直在学习javascript,也有看过<犀利开发Jquery内核详解与实践>,对这本书的评价只有两个字犀利,可能是对javascript理解的还不够透彻异或是自己太笨,更多的是自己不擅于 ...
- My Package
一.新建一文件夹,名称为MyBase,存放Java的基本类. 二.在MyBase包中创建基本类Base.java. package MyBase; public class Base { public ...
- angular.js ng-class-even ng-class-odd ng-cloak(没啥技术含量)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- CPS冥想 - 1 重新审视CPS
这篇文章是在阅读Eric Lippert大神的MSDN Blog文章时同步写成的,其中主要是各种翻译,同时还混杂自己阅读文章的笔记和感想. 原博文地址 http://blogs.msdn.com/b/ ...
- c# 高效率导出多维表头excel
[DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThread ...
- 异常Throwable类
所有异常类型都是Throwable类的子类,它派生出两个子类 Error和Exception Error类:表示紧靠程序本身无法恢复的严重错误,如内存溢出,动态链接失败,虚拟机错误 ...
- linker command failed with exit code 1 (use -vto see invocation)
报这样的错误可能是同一个.m文件同时存在,要先把你新添加的.m文件彻底删除 Move to Trash 点击这个删除.然后clear一下,再在重新添加你所需要的文件即可解决.这次添加不要推进来,需要在 ...
- scp远程复制
scp 源 目标 -r 复制目录 scp -r root@ip:/XXX/path /XXX 注意:复制目录,包括该目录本身,目的地址无需再加该目录
- scrollWidth的巧妙运用
再了无生趣的工作也是能够帮助我们提高的~ 最近工作比较无聊,于是就想到了写一个滚动条插件,在借鉴了mCustomerScrollbar这个组件之后我简单的写了一个类似的,当然,相比于它的2000多行代 ...