springbbot excel导出poi框架
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

/**
 * 
 * 导出XLS文件
 *
 */
public class GradesXLS {

	private String path;

	public GradesXLS() {
		super();
	}
	
	//构造函数获取保存excel路径
	public GradesXLS(String path) {
		super();
		this.path = path;
	}
	
	
	public static boolean createFile(String destFileName) {  
        File file = new File(destFileName);  
        if(file.exists()) {  
            System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");  
            return false;  
        }  
        if (destFileName.endsWith(File.separator)) {  
            System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");  
            return false;  
        }  
        //判断目标文件所在的目录是否存在  
        if(!file.getParentFile().exists()) {  
            //如果目标文件所在的目录不存在,则创建父目录  
            System.out.println("目标文件所在目录不存在,准备创建它!");  
            if(!file.getParentFile().mkdirs()) {  
                System.out.println("创建目标文件所在目录失败!");  
                return false;  
            }  
        }  
        //创建目标文件  
        try {  
            if (file.createNewFile()) {  
                System.out.println("创建单个文件" + destFileName + "成功!");  
                return true;  
            } else {  
                System.out.println("创建单个文件" + destFileName + "失败!");  
                return false;  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());  
            return false;  
        }  
    }  
	
	
	public Boolean CreateExcel(List<Object[]> dataList, String[] column, String clientName, HttpServletResponse response , HttpServletRequest  request) throws Exception {
		//创建一个工作簿
		HSSFWorkbook workBook = new HSSFWorkbook();
		//创建一个工作表,名为:第一页
		HSSFSheet sheet = workBook.createSheet(clientName);
		//设置单元格的宽度(0:表示第一行的第一个单元格,1:第一行的第二个单元格)
		sheet.setColumnWidth((short) 0, 3500);
		sheet.setColumnWidth((short) 1, 5000);
		sheet.setColumnWidth((short) 2, 5000);
		//创建一个单元格,从0开始
		HSSFRow row = sheet.createRow((short) 0);
		//构造一个数组设置第一行之后的单元格
		HSSFCell[] cell = new HSSFCell[column.length];
		for (int i = 0; i < column.length; i++) {
			cell[i] = row.createCell(i);
			cell[i].setCellValue(column[i]);
		}
		
		//获得从数据库中查询出来的数据
		if (dataList != null && dataList.size() > 0) {
			//循环list中的数据
			for (int i = 0; i < dataList.size(); i++) {
				Object[] objs = dataList.get(i);
				HSSFRow dataRow = sheet.createRow(i + 1);
				HSSFCell data[] = new HSSFCell[column.length];
				for (int j = 0; j < column.length; j++) {
					data[j] = dataRow.createCell(j);
					String info = String.valueOf(objs[j]);
					System.out.println("GradesXLS:" + info);
					data[j].setCellValue((info == null) ? "" : info);
				}
			 }
			
			try {
//				String fileName = clientName + "-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
				//设置日期格式
				//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				// new Date()为获取当前系统时间,也可使用当前时间戳
				//String date = df.format(new Date());
				long date = System.currentTimeMillis();
				String fileName = clientName + "-" + date + ".xls";
				path = request.getSession().getServletContext().getRealPath("/"); 
				File file = new File(path+fileName);
				if(!file.exists()) {
					GradesXLS.createFile(path+fileName);
				}
//				response.setContentType("application/vnd.ms-excel");
//				response.setCharacterEncoding("utf-8");
//				response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("gbk"), "iso8859-1"));
//				
//				OutputStream os = response.getOutputStream();
				
				FileOutputStream out = new FileOutputStream(file);
				workBook.write(out);
				out.flush();
				out.close();
				return true;
			} catch (FileNotFoundException e) {
				// TODO: handle exception
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace();
				return false;
			}
		} 
		return false;
	}
	
}

bean层的实体类

public class User {

	private int id ;
	
	private String name ;
	
	private String head ;
	
	private int sex ;
	
	private String phone ;
	
	
	
	

	public User(int id, String name, String head, int sex, String phone) {
		super();
		this.id = id;
		this.name = name;
		this.head = head;
		this.sex = sex;
		this.phone = phone;
	}

	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 getHead() {
		return head;
	}

	public void setHead(String head) {
		this.head = head;
	}


	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	
	
}

controller,测试

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.iot.excel.bean.User;
import com.iot.excel.config.GradesXLS;


@RestController
public class ExcelController {

	@GetMapping("/execl")
	public void getExcel(HttpServletRequest request, HttpServletResponse response) {
		GradesXLS gradesXLS =new GradesXLS();
		String[] column = {"id","name","head","sex","phone"};
		String clientName = "学生表";
		List<User> user = new ArrayList<>();
		User user1 = new User(1, "111", "111", 1, "111"); 
		User user2 = new User(2, "222", "222", 0, "222"); 
		User user3 = new User(3, "333", "333", 0, "333");
		user.add(user1);
		user.add(user2);
		user.add(user3);
		
		List<Object[]> dataList = new ArrayList<>();
		
		for (User u : user) {
			Object[] obj = {u.getId(),u.getName(),u.getHead(),getClass(),u.getSex(),u.getPhone()};
			dataList.add(obj);
		}
		
		try {
			gradesXLS.CreateExcel(dataList, column, clientName, response,request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

阅读更多
文章标签: java导出execl
个人分类: java导出execl 后台
想对作者说点什么? 我来说一句

POI + Struts2 实现Excel导出工具包

2018年05月23日 1.44MB 下载

没有更多推荐了,返回首页

不良信息举报

springbbot excel导出poi框架

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭