java POI excel导出

1.所需的jar
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
2.Excel对象
package com.shy.springmvc.util;

import java.util.List;

public class ExcelParam {
	 String name;
	    int width;
	    String font;
	    String[] headers;
	    /**
	     * 导出数据的样式
	     * 1:String left;
	     * 2:String center
	     * 3:String right
	     * 4 int  right
	     * 5:float ###,###.## right
	     * 6:number: #.00% 百分比 right
	     */
	    int[] ds_format;
	    /**
	     * 每列表格的宽度,默认为256 * 14
	     */
	    int[] widths;
	    List<String[]> data;

	    private ExcelParam() {

	    }
	    //使用Builder模式,设置默认参数和必填参数
	    public static class Builder {
	        String name;
	        int width = 256 * 14;
	        String font = "微软雅黑";
	        String[] headers;
	        int[] ds_format;
	        int[] widths;
	        List<String[]> data;

	        public Builder(String name) {
	            this.name = name;
	        }

	        public Builder font(String font) {
	            this.font = font;
	            return this;
	        }

	        public Builder width(int width) {
	            this.width = width;
	            return this;
	        }

	        public Builder headers(String[] headers) {
	            this.headers = headers;
	            return this;
	        }

	        public Builder ds_format(int[] ds_format) {
	            this.ds_format = ds_format;
	            return this;
	        }

	        public Builder widths(int[] widths) {
	            this.widths = widths;
	            return this;
	        }

	        public Builder data(List<String[]> data) {
	            this.data = data;
	            return this;
	        }

	        public ExcelParam build() {
	            ExcelParam excelParam = new ExcelParam();
	            excelParam.name = this.name;
	            excelParam.data = this.data;
	            excelParam.widths = this.widths;
	            excelParam.ds_format = this.ds_format;
	            excelParam.headers = this.headers;
	            excelParam.font = this.font;
	            excelParam.width = this.width;
	            return excelParam;
	        }
	    }
}
3.Excel导入工具类
package com.shy.springmvc.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {
	private ExcelUtil() {
    }

    public static void export(ExcelParam excelParam, HttpServletResponse response) throws IOException {
        if (excelParam.widths == null) {
            excelParam.widths = new int[excelParam.headers.length];
            for (int i = 0; i < excelParam.headers.length; i++) {
                excelParam.widths[i] = excelParam.width;
            }
        }
        if (excelParam.ds_format == null) {
            excelParam.ds_format = new int[excelParam.headers.length];
            for (int i = 0; i < excelParam.headers.length; i++) {
                excelParam.ds_format[i] = 1;
            }
        }
        //创建一个工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        int rowCount = 0;
        int rowCount2 = 0;
        //创建一个sheet
        HSSFSheet sheet = wb.createSheet("用户表");
        //创建第二一个sheet
        HSSFSheet sheet2 = wb.createSheet("说明");
        if (excelParam.headers != null) {
            HSSFRow row = sheet.createRow(rowCount);
            HSSFRow row2 = sheet2.createRow(rowCount2);
            //表头样式
            HSSFCellStyle style = wb.createCellStyle();
            HSSFFont font = wb.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setFontHeightInPoints((short) 11);
            style.setFont(font);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            
            for (int i = 0; i < excelParam.headers.length; i++) {
                sheet.setColumnWidth(i, excelParam.widths[i]);
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(excelParam.headers[i]);
                cell.setCellStyle(style);
            }
            
            for (int i = 0; i < 3; i++) {
                sheet2.setColumnWidth(i, excelParam.widths[0]);
                HSSFCell cell = row2.createCell(i);
                cell.setCellValue("admin");
                cell.setCellStyle(style);
            }
            rowCount++;
            rowCount2++;
        }
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //表格主体  解析list
        for (int i = 0; i < excelParam.data.size(); i++) {  //行数
            HSSFRow row = sheet.createRow(rowCount);
            for (int j = 0; j < excelParam.headers.length; j++) {  //列数
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(excelParam.data.get(i)[j]);
                cell.setCellStyle(style);
            }
            rowCount++;
        }
        //表2
        for (int i = 1; i < 10; i++) {  //行数
            HSSFRow row = sheet2.createRow(rowCount2);
            for (int j = 0; j < 3; j++) {  //列数
                HSSFCell cell = row.createCell(j);
                cell.setCellValue("lisi");
                cell.setCellStyle(style);
            }
            rowCount2++;
        }
        //设置文件名
        //String fileName = excelParam.name + ".xls";
        String fileName = "users.xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Pragma", "No-cache");
        OutputStream outputStream = response.getOutputStream();
        wb.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
4.调用
package com.shy.springmvc.controller;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

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

import com.alibaba.fastjson.JSONObject;
import com.shy.springmvc.dao.UserInfoDao;
import com.shy.springmvc.entity.UserInfo;
import com.shy.springmvc.util.ExcelParam;
import com.shy.springmvc.util.ExcelUtil;

@RequestMapping(value="/excel")
@Controller
public class ExcelController {
	Logger log = Logger.getLogger(ExcelController.class);
	@Autowired
	UserInfoDao userInfo;
	@RequestMapping(value="/poi")
	@ResponseBody
	public JSONObject POIExcel(HttpServletResponse response) {
		JSONObject returnJson = new JSONObject(); 
		List<UserInfo> userInfos = userInfo.findUserInfo();
        String[] heads = {"序号", "用户名称", "地址", "性别", "密码", "角色ID"};
        List<String[]> data = new LinkedList<String[]>();
        for (int i = 0; i < userInfos.size(); i++) {
            UserInfo user = userInfos.get(i);
            String[] temp = new String[6];
            temp[0] = String.valueOf(i + 1);
            temp[1] = user.getUser_name();
            temp[2] = user.getAddress();
            temp[3] = user.getSex()+"";
            temp[4] = user.getUser_pass();
            temp[5] = user.getRole_id()+"";
            data.add(temp);
        }
        try {
        	ExcelParam param = new ExcelParam.Builder("操作日志").headers(heads).data(data).build();
        	ExcelUtil.export(param, response);
        	log.info(data);
        	returnJson.put("DATA", data);
        	returnJson.put("STATUS", "SUCCESS");
			returnJson.put("MSG", "导出成功");
		} catch (Exception e) {
			returnJson.put("STATUS", "ERROR");
			returnJson.put("MSG", "导出异常");
			return returnJson;
		}
		return returnJson;
	}
}
5.导出结果

猜你喜欢

转载自blog.csdn.net/shy415502155/article/details/80492713