1.导入jar包,以下使用的是maven导入jar包
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
2.再springmvc配置文件中添加视图解析器
<!-- excel视图解析 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="0"/>
</bean>
注:这里的order注入的值是优先级,越靠前越优先
3.添加导出视图类
package com.view;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractExcelView;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@SuppressWarnings("deprecation")
public class ViewExcel extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
//获取日期
Date now =new Date();//获取日期
SimpleDateFormat data = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = data.format(now).toString()+".xls";
response.setCharacterEncoding("UTF-8");
response.setContentType("application/ms-excel");
response.setHeader("Content-Disposition", "inline; filename="+new String(fileName.getBytes(),"iso8859-1"));
OutputStream outputStream = response.getOutputStream();
// 新建工作表
HSSFSheet sheet = workbook.createSheet("sheet1");
HSSFRow header = sheet.createRow(0);
// 标题数据
String[] DataTitles = (String[]) model.get("DataTitle");
GetList(header,DataTitles);
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yyyy"));
int rowNumber = 1;
//数据信息
@SuppressWarnings("unchecked")
List<String[]> DataLists = (List<String[]>) model.get("DataList");
for (String[] list : DataLists) {
HSSFRow row = sheet.createRow(rowNumber++);
GetList(row,list);
}
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
public void GetList(HSSFRow row,String[] list){
int i = 0;
for(String data : list){
row.createCell(i).setCellValue(data);
i++;
}
}
}
4.添加控制器
public ModelAndView demo(){
Map<String, Object> model = new HashMap<String, Object>();
List<String[]> userList = new ArrayList<String[]>();
User user = new User("1", "Tome", "Tom@qq.com", "123456");
model.put("DataList", userList);
model.put("DataTitle", new String[]{"ID","用户名","邮箱","密码"});
return new ModelAndView(new ViewExcel(), model);
}