1.导包 或直接注入maven依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
2、写一个工具类或者直接写在service中,本人是写在了service中,如果有多个需要导出导入的的地方,那就最好写成工具类。
service层
//导出
public void export(List<ExamcountWithBLOBs> exam,OutputStream out);
//导入
public List<ExamcountWithBLOBs> importExcel(MultipartFile file);
serviceImpl
//这是将标签替换,单独抽取了出来,方便调用
public String replaceP(String content){
//它遇到\r\n的时候会自动换行
//获取要导出的内容把里面的<P> 换成"" ,把</P>换成\r\n
//把$nbsp; 替换成空格
content=content.replaceAll("<p>","");
content=content.replaceAll(" ", " ");
content=content.replaceAll("</p>", "\r\n");
return content;
}
//导出
public void export(List<ExamcountWithBLOBs> exam,OutputStream out){
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet hs = wb.createSheet("考试信息统计表");
HSSFRow hr = hs.createRow(0);
HSSFCell hc = hr.createCell(0);
//第一行表头
hc.setCellValue("考试统计列表");
//合并单元格
hs.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));
//设置列宽
//第一个属性是第几列,第二个是列的宽度
// 由于下面定义的列是以数组的形式存在,所以列数是从 0 开始的
hs.setColumnWidth(0, 20*256);
hs.setColumnWidth(1, 20*256);
hs.setColumnWidth(2, 50*256);
hs.setColumnWidth(3, 50*256);
hs.setColumnWidth(4, 50*256);
hs.setColumnWidth(5, 50*256);
hs.setColumnWidth(6, 50*256);
hs.setColumnWidth(7, 50*256);
hs.setColumnWidth(8, 50*256);
//设置格式
HSSFCellStyle style=wb.createCellStyle();
//自动换行
style.setWrapText(true);
//水平居中
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//垂直居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//合并单元格
HSSFRow hf2 = hs.createRow(1);
//第二行每列的列名
String [] title = {"班级","讲师","本周课程进度","当前班级学生情况概述","本周考试内容","本周考试成绩及分析说明","班级学员问题及解决情况","总结","时间"};
for (int i = 0; i < title.length; i++) {
hf2.createCell(i).setCellValue(title[i]);
}
//后面有多少行由list的size决定
for(int i=0; i<exam.size();i++){
//创建行
HSSFRow rowi = hs.createRow(i+2);
//创建列
//第一列
HSSFCell cell0=rowi.createCell(0);
cell0.setCellStyle(style);
String cname=exam.get(i).getC_name();
cell0.setCellValue(cname);
HSSFCell cell1=rowi.createCell(1);
//调用格式
cell1.setCellStyle(style);
//获取内容
String uname=exam.get(i).getUser().getuName();
//将内容添加到对应的列
cell1.setCellValue(uname);
/*rowi.createCell(0).setCellValue(exam.get(i).getC_name());
rowi.createCell(1).setCellValue(exam.get(i).getUser().getuName());*/
HSSFCell cell2=rowi.createCell(2);
cell2.setCellStyle(style);
String progress=exam.get(i).geteStudyprogress();
progress=replaceP(progress);
cell2.setCellValue(progress);
HSSFCell cell3=rowi.createCell(3);
cell3.setCellStyle(style);
String studycase=exam.get(i).geteStudycase();
//调用标签替换的方法,替换掉数据库中存在的多余的标签
//如果有另外的标签需要替换自己添加进替换方法中
studycase=replaceP(studycase);
cell3.setCellValue(studycase);
HSSFCell cell4=rowi.createCell(4);
cell4.setCellStyle(style);
String content=exam.get(i).geteExamcontent();
content=replaceP(content);
cell4.setCellValue(content);
HSSFCell cell5=rowi.createCell(5);
cell5.setCellStyle(style);
String gradeandanalyze=exam.get(i).geteGradeandanalyze();
gradeandanalyze=replaceP(gradeandanalyze);
cell5.setCellValue(gradeandanalyze);
HSSFCell cell6=rowi.createCell(6);
cell6.setCellStyle(style);
String program=exam.get(i).geteProgramandanalyze();
program=replaceP(program);
cell6.setCellValue(program);
HSSFCell cell7=rowi.createCell(7);
cell7.setCellStyle(style);
String count=exam.get(i).geteCount();
count=replaceP(count);
cell7.setCellValue(count);
//时间一定要用 toLocaleString()方法转换为String格式,不能用toString()方法 rowi.createCell(8).setCellValue(exam.get(i).geteDate().toLocaleString());
}
//下载
try {
wb.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//导入
/**MultipartFile file 设置成MultipartFile 类型是因为在springmvc-action.xml中设置文件上传大小的beand的类型为MultipartFile,所以只要跟文件上传有关的file都必须设置为MultipartFile 类型
如果设置一边是是MultipartFile 类型,另外地方设置为File类型,则会造成 java.lang.File.init的BUG出现,所以最好都都设定为MultipartFile类型
<!-- 文件上传的
id不能随便起 必须是multipartResolver
-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 文件上传的大小 -->
<property name="maxUploadSize" value="99999999"></property>
</bean>
**/
public List<ExamcountWithBLOBs> importExcel(MultipartFile file){
List<ExamcountWithBLOBs> list = new ArrayList<ExamcountWithBLOBs>();
try {
InputStream in =file.getInputStream();
Workbook wb = new HSSFWorkbook(in);
Sheet sheet = wb.getSheetAt(0);
//定义一个list来获取内容
//获取列 行 内容
for (Row row : sheet) {
//第一行 第二行不获取
if(row.getRowNum()<2){
continue;
}
//定义一个user对象
ExamcountWithBLOBs exam=new ExamcountWithBLOBs();
exam.setC_name(row.getCell(1).getStringCellValue());
exam.seteStudyprogress(row.getCell(2).getStringCellValue());
exam.seteStudycase(row.getCell(3).getStringCellValue());
exam.seteExamcontent(row.getCell(4).getStringCellValue());
exam.seteGradeandanalyze(row.getCell(5).getStringCellValue());
exam.seteProgramandanalyze(row.getCell(6).getStringCellValue());
exam.seteCount(row.getCell(7).getStringCellValue());
/*exam.seteDate(new Date(row.getCell(8).getStringCellValue()));*/
//放到list里
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
exam.seteDate(sdf.parse(row.getCell(8).getStringCellValue()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list.add(exam);
}
return list;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
controller
//导出
//导出excel 导出的controller方法返回值类型为void
@RequestMapping("/exam/exportExcel.action")
public void exportExcel(HttpServletResponse response,String start,String end){
//这是根据时间查询,可以随意换成其他查询方式
Map<String, String> map=new HashMap<String, String>();
map.put("time1",start );
map.put("time2",end);
List<ExamcountWithBLOBs> list=examService.findTimeToTime(map);
OutputStream out=null;
try {
out=response.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//告诉浏览器以下载 的方式打开
response.setHeader("Content-disposition", "attachment;filename=exam.xls");
//设置响应类型
response.setContentType("application/msexcel");
examService.export(list, out);
}
//导入excel MultipartFile Importfile这个Importfile一定要跟jsp页面中的file的name相对应
@RequestMapping("/exam/imporExcel.action")
public String importExcel(MultipartFile Importfile){
//导入File 获取file 从页面获取
System.out.println(Importfile+"sssssssssssssss");
List<ExamcountWithBLOBs> list=examService.importExcel(Importfile);
//利用循环添加
for (ExamcountWithBLOBs exam : list) {
examService.add(exam);
}
return "/kstj/kstj";
}
jsp页面
//导出
function doExportExcel(){
window.open("${pageContext.request.contextPath }/exam/exportExcel.action?start="+t2+"&end="+t1);
}
<input type='button' value='导出' class='s_button' onclick='doExportExcel()''/>
//导入 form的类型enctype="multipart/form-data"一定要设置
<form action="${pageContext.request.contextPath }/exam/imporExcel.action" method="post" enctype="multipart/form-data">
<input name="Importfile" type="file">
<input type="submit" value="导入" />
</form>