您的位置:首页 > 编程语言 > Java开发

springMVC中使用POI方式导出excel至客户端、服务器实例

2015-07-17 17:06 651 查看
  Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

  这里的方法支持导出excel至项目所在服务器,或导出至客户端浏览器供用户下载,下面我把两个实例都放出来。

1.下载所需POI的jar包,并导入项目。

2.添加一个User类,用于存放用户实体,类中内容如下:

package com.mvc.po;

public class User {
private int id;
private String name;
private String password;
private int age;

public User() {

}

public User(int id, String name, String password, int age) {
this.id = id;
this.name = name;
this.password = password;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}


3.添加一个UserController类,类中内容如下:

package com.mvc.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mvc.po.User;
import com.mvc.service.UserService;

@Controller
public class UserController {

@Autowired
private UserService userService;

@RequestMapping("/export.do")
public @ResponseBody String export(HttpServletResponse response){
response.setContentType("application/binary;charset=UTF-8");
try{
ServletOutputStream out=response.getOutputStream();
String fileName=new String(("UserInfo "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(),"UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
String[] titles = { "用户编号", "用户姓名", "用户密码", "用户年龄" };
userService.export(titles, out);
return "success";
} catch(Exception e){
e.printStackTrace();
return "导出信息失败";
}
}
}


4.添加一个接口类UserService和实现类UserServiceImpl,类中内容如下:

package com.mvc.service;

import javax.servlet.ServletOutputStream;
import com.mvc.po.User;

public interface UserService {
public void export(String[] titles, ServletOutputStream out);
}


package com.mvc.service.impl;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletOutputStream;

import com.mvc.dao.UserDAO;
import com.mvc.po.User;
import com.mvc.service.UserService;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserDAO userDAO;

@Override
public void export(String[] titles, ServletOutputStream out) {
try{
// 第一步,创建一个workbook,对应一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet hssfSheet = workbook.createSheet("sheet1");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow hssfRow = hssfSheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle hssfCellStyle = workbook.createCellStyle();
//居中样式
hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

HSSFCell hssfCell = null;
for (int i = 0; i < titles.length; i++) {
hssfCell = hssfRow.createCell(i);//列索引从0开始
hssfCell.setCellValue(titles[i]);//列名1
hssfCell.setCellStyle(hssfCellStyle);//列居中显示
}

// 第五步,写入实体数据
List<User> users = userDAO.query();

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
if(users != null && !users.isEmpty()){
for (int i = 0; i < users.size(); i++) {
hssfRow = hssfSheet.createRow(i+1);
User user = users.get(i);

// 第六步,创建单元格,并设置值
int userid = 0;
if(user.getId() != 0){
userid = user.getId();
}
hssfRow.createCell(0).setCellValue(userid);
String username = "";
if(user.getName() != null){
username = user.getName();
}
hssfRow.createCell(1).setCellValue(username);
String password = "";
if(user.getPassword() != null){
password = user.getPassword();
}
hssfRow.createCell(2).setCellValue(password);
int age = 0;
if(user.getAge() != 0){
age = user.getAge();
}
hssfRow.createCell(3).setCellValue(age);
}
}

// 第七步,将文件输出到客户端浏览器
try {
workbook.write(out);
out.flush();
out.close();

} catch (Exception e) {
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
throw new Exception("导出信息失败!");
}
}
}


5.添加一个接口类UserDAO和实现类UserDAOImpl,类中内容如下:

package com.mvc.dao;

import java.util.List;
import com.mvc.po.User;

public interface UserDAO {
List<User> query();
}


package com.mvc.dao.impl;

import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mvc.dao.UserDAO;
import com.mvc.po.User;

import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

@Repository
public class UserDAOImpl implements UserDAO {

@Autowired
private JdbcTemplate jdbcTemplate;

public List<User> query() {
return this.jdbcTemplate.query("select * from student",
new RowMapper<User>() {
public User mapRow(ResultSet rs, int arg1)
throws SQLException {
return new User(rs.getInt("sId"),
rs.getString("sName"), rs.getString("sPwd"), rs
.getInt("sAge"));
}
});
}
}


  这样就完成了excel导出至客户端浏览器,当然有时候也会用到导出excel至服务器上。只需要对本文步骤4中的第七步文件输出方式进行修改,如下:

// 第七步,将文件存到指定位置
try {
FileOutputStream fileOutputStream = new FileOutputStream("C:/user.xls");//指定路径与名字和格式
workbook.write(fileOutputStream);//讲数据写出去
fileOutputStream.close();//关闭输出流
} catch (Exception e) {
e.printStackTrace();
}


  然后去除controller类中的out参数设置就ok了。也可以看出其实两种方式只是最终保存方式不同,其他步骤是共通的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: