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 ...
随机推荐
- Token验证失败
Token验证失败 微信 微信公众平台开发 Token校验失败 URL Token原文 http://www.cnblogs.com/txw1958/p/token-verify.html Token ...
- 【Java数据格式化】使用DecimalFormat 对Float和double进行格式化
格式化包括如下内容: 基本用法 金钱格式: 科学计数法: 百分比计数法: 嵌入文本: package com.sssppp.NumberFormat; import java.text.Decimal ...
- struts1 Demo
每次都会忘记一些东西,反复查找原因,其实struts1很简单,可是不去巩固也很容易忘记并且犯错误.这是一个最简单的登录Demo. 1.建立web工程,引入struts1.2包 2.建package:a ...
- 对ASP.NET运行机制之 一般处理程序ashx的学习
一般处理程序(HttpHandler)是·NET众多web组件的一种,ashx是其扩展名.其中一个httpHandler接受并处理一个http请求,类比于Java中的servlet.类比于在Java中 ...
- iOS NSNotification的使用
如果在一个类中想要执行另一个类中的方法可以使用通知 1.创建一个通知对象:使用notificationWithName:object: 或者 notificationWithName:object:u ...
- [IIS]IIS扫盲(六)
一:聊天室 聊天室的种类有很多,免费的聊天室也有很多,这些聊天室的ASP源码从网上都可以下载得到,我们就以毒爱聊天室为版本来教大家做.好,大家先下载毒爱聊天室,当然,本站软件下载里就有下载,下载的是 ...
- XE6移动开发环境搭建之IOS篇(5):解决Windows和虚拟机下Mac OSX的共享问题(有图有真相)
网上能找到的关于Delphi XE系列的移动开发环境的相关文章甚少,本文尽量以详细的图文内容.傻瓜式的表达来告诉你想要的答案. 原创作品,请尊重作者劳动成果,转载请注明出处!!! 在安装XE6 PAS ...
- Mysql备份迁移——MySqlBackup(.net)——(无法解决视图嵌视图报错)
这里是利用MySqlBackup,可以再nuget中下载. 无法解决视图嵌视图报错的问题,只导表跟数据比较合适,如果有视图嵌视图,请参照Mysql备份迁移——Mysqldump(.NET调用Mysql ...
- 洛谷P3374 【模板】树状数组 1
P3374 [模板]树状数组 1 140通过 232提交 题目提供者HansBug 标签 难度普及/提高- 提交 讨论 题解 最新讨论 题目描述有误 题目描述 如题,已知一个数列,你需要进行下面两 ...
- python学习笔记:文件操作和集合(转)
转自:http://www.nnzhp.cn/article/16/ 这篇博客来说一下python对文件的操作. 对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句 ...