前段时间在学校做生产实习的时候,需要将前段显示出来的数据导出到excel表格中,在网上看了很多博客,发现要么是要花钱下载的要么就是代码不全而且解释不清楚的,花了两天时间自己整理和写了一个可以勾选数据并且能实现导出到excel的功能.
主要实现是从前端获取数据在后端下载.
进入主题:
这篇博客先写个简单的例子来理解下大概的流程,例子非常的简单非常的便于理解.
第一步搭建环境导包:(pom.xml中)
pom.xml文件
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
第二步:导入包后等待maven更新一下,等你的idea把包都导入进去.
第三步:
扩展一下知识点
这里说一个小小的扩展:
POI 提供了对2003版本的Excel的支持 ---- HSSFWorkbook
POI 提供了对2007版本以及更高版本的支持 ---- XSSFWorkbook
这个不用犯愁很好记: 2003版本的就记住一个H,2007以及更高版本的就记住一个X!
第四步:上代码
先创建个实体类方便我们建个表格填里面的数据.
Score.java即pojo层
import java.io.Serializable;
public class Score implements Serializable {
private String name;//姓名
private Integer chinese;//语文
private Integer mathematics;//数学
private Integer english;//英语
public Score() {
}
public Score(String name, Integer chinese, Integer mathematics, Integer english) {
this.name = name;
this.chinese = chinese;
this.mathematics = mathematics;
this.english = english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getChinese() {
return chinese;
}
public void setChinese(Integer chinese) {
this.chinese = chinese;
}
public Integer getMathematics() {
return mathematics;
}
public void setMathematics(Integer mathematics) {
this.mathematics = mathematics;
}
public Integer getEnglish() {
return english;
}
public void setEnglish(Integer english) {
this.english = english;
}
}
下面编写控制器类
ScoreController.java
@Autowired
public static List<Score> list = new ArrayList<>(); //定义的一个全局变量方便待会把数据传入前端
@Autowired
public static Random random = new Random(); //定义一个静态的随机数主要用于下面产生一个数据表
/**
* 成绩列表----为了更加的好操作,手动产生一个学生信息的表格,
* 方便大家不需要连接数据库直接可以在前段显示一个拥有数据的表格
* @return
*/
@RequestMapping("/list")
public ModelAndView list() {
ModelAndView mv = new ModelAndView();//创建一个模型视图
for (int i = 0 ; i < 10 ; i++ ){ //利用循环产生10个数据
String name = "测试员 " + (i + 1);//在姓名列中动态的加1
int chinese = random.nextInt(100);
int mathematics = random.nextInt(100);
int english = random.nextInt(100);
Score score = new Score(name , chinese , mathematics , english);
list.add(score);
}
mv.addObject("list" , list);
mv.setViewName("list");
return mv;
}
/**
* 导出数据
* @return
*/
@RequestMapping("/export")
public String export(HttpServletResponse response, HttpServletRequest request){
response.setContentType("text/html;charset=UTF-8");
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
StringBuffer fileNameBuffer = new StringBuffer("");
fileNameBuffer.append("成绩表").append("-").append(sdf.format(new Date())).append(".xls");
String filename = URLEncoder.encode(fileNameBuffer.toString(), "UTF-8");
//定义导出信息
//表名定义
String shellNameObjects[] = {
"成绩表"
};
//列名定义
String shellHeaderObjects[][] = new String[][]{
{"姓名", "语文", "数学" , "英语"},
};
//转换拿到的checkid数组
String checkid=request.getParameter("checkId");
System.out.println("接收的checkid:"+checkid);
System.out.println("转换的整型数组:");
String[] str=checkid.split(",");//切割字符串返回数组
int[] ids=new int[str.length];
if (str.length>0){//遍历一个数组然后来接收这个数组,用来强转
for (int i=0;i< str.length;i++){
ids[i]=Integer.parseInt(str[i]);//强制转换INT类型的数组
System.out.println(ids[i]);
}
}
//创建工作表
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
//创建表格名称
HSSFSheet sheet0 = wb.createSheet(shellNameObjects[0]);
//设置每行每列单元格大小
sheet0.autoSizeColumn(1, true);
//单独设置每列的宽度:这个非常有用,假设有些列内容过长时,就需要设置一定的长度显示内容了。不设置则使用默认宽度。
sheet0.setColumnWidth(0 , 25 * 256);
//sheet0.setColumnWidth(2 , 80 * 256);
//创建(填充)表格标题(表格第一行)
HSSFRow sheet0HeaderRow = sheet0.createRow(0);
sheet0HeaderRow.setHeightInPoints(20);//目的是想把行高设置成20px
for (int i = 0; i < shellHeaderObjects[0].length; i++) {
HSSFCell cell = sheet0HeaderRow.createCell((short) i);
cell.setCellValue(shellHeaderObjects[0][i]);
cell.setCellStyle(style);
}
if(ids[0]==-1){
System.out.println("没有选中数据导出全部2123");
//填充表格(单元格)内容
if (null != list && list.size() > 0)
{
//从表格第二行开始填充,因为第一行已经填充标题了
int index = 1;
for (Score bean: list){
HSSFRow sheetRow = sheet0.createRow(index);
sheetRow.setHeightInPoints(30);//目的是想把行高设置成20px
sheetRow.createCell(0).setCellValue(bean.getName());
sheetRow.createCell(1).setCellValue(bean.getChinese());
sheetRow.createCell(2).setCellValue(bean.getMathematics());
sheetRow.createCell(3).setCellValue(bean.getEnglish());
index++;
}
}
}
else{
//填充表格(单元格)内容
if (null != list && list.size() > 0)
{
//从表格第二行开始填充,因为第一行已经填充标题了
int index = 1 ;
for (int k = 0; k < ids.length; k++) {
Score bean= list.get(ids[k]-1);
{
System.out.println("ids["+k+"]"+ids[k]+ "-----等于");
HSSFRow sheetRow = sheet0.createRow(index);
sheetRow.setHeightInPoints(30);//目的是想把行高设置成20px
sheetRow.createCell(0).setCellValue(bean.getName());
sheetRow.createCell(1).setCellValue(bean.getChinese());
sheetRow.createCell(2).setCellValue(bean.getMathematics());
sheetRow.createCell(3).setCellValue(bean.getEnglish());
index++;
}
}
}
}
// 回去输出流
OutputStream out = response.getOutputStream();
response.setHeader("Cache-Control", "private");
response.setHeader("Pragma", "private");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-disposition", "attachment;filename=" + filename);
wb.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}