导出Excel

springboot框架利用poi导出Excel


需要引入的jar包

		<!-- HSSF需要引入的 -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>RELEASE</version>
		</dependency>

		<!-- XSSF需要引入的 -->
		<dependency>
			<groupId>org.apache.xmlbeans</groupId>
			<artifactId>xmlbeans</artifactId>
			<version>2.6.0</version>
		</dependency>

代码

		package cn.zkun.exportExcell;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.ibatis.javassist.expr.NewArray;
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.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Excel {

	@RequestMapping("downExcel")
	@ResponseBody
	public String down(HttpServletRequest request, HttpServletResponse response) {
		System.err.println("//");
		List<Map<String, Object>> listresult = new ArrayList<Map<String, Object>>();
		for (int j = 0; j < 10; j++) {
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i = 1; i < 5; i++) {
				map.put("rowKey" + i, "第" + j + "行" + i + "列");
			}
			map.put("j", j);
			listresult.add(map);
		}
		String name = downUserList(listresult, request, response);
		return name;
	}

	/**
	 * 用户列表导出
	 * 
	 * @param userForm
	 */
	private String downUserList(List<Map<String, Object>> listresult,
	 HttpServletRequest request,HttpServletResponse response) {
		String csvFile = "G:\\Excel";
		// getTime()是一个返回当前时间的字符串,用于做文件名称
		String name = new SimpleDateFormat().format(new Date()) + "2";
		// csvFile是我的一个路径,自行设置就行
		String ys = csvFile + "//" + name + ".xlsx";
		String[] titel = {"序号", "学院", "任课教师数", "调课次数", "调课原因" };
		String[] columnName= {"j","rowKey1","rowKey2","rowKey3","rowKey4"};
		int[] columnWidth= {10*100,10*200,10*300,10*400,10*500};
		// 1.生成Excel
		HSSFWorkbook userListExcel =Export(listresult, 60000, "武汉理工大学调课情况统计表", 				                                                titel, columnName, columnWidth);
		OutputStream os = null;
		try {
			// 输出成文件
			File file = new File(csvFile);
			if (file.exists() || !file.isDirectory()) {
				file.mkdirs();
			}
			// TODO 生成的wb对象传输
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(ys, "UTF-8"));
			response.setContentType("application/msexcel");
			os = response.getOutputStream();
			userListExcel.write(os);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return name;
	}
	
	/**
	 * 
	 * @param list
	 * @param sum           sheet数据条数
	 * @param header        表头
	 * @param titel	        列名
	 * @param columnName    list集合中map的key
	 * @param columnWidth	列宽
	 * @return
	 */
	public HSSFWorkbook Export(List list,int sum,String header,String[] titel,String[] columnName,int[] columnWidth) {
		// 1.创建HSSFWorkbook,一个HSSFWorkbook对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 2.在workbook中添加一个sheet,对应Excel文件中的sheet
		int count=0;//统计生成sheet数量
		Object obj=null;
		for (int k = 0; k <= list.size() / sum; k++) {
			HSSFSheet sheet = wb.createSheet("等级考试成绩表"+(k+1));
			// 创建一个居中的样式
			HSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setBorderBottom((short) 1);
			style.setBorderLeft((short) 1);
			style.setBorderRight((short) 1);
			style.setBorderTop((short) 1);
			// 合并
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, titel.length-1));
			// 设置列宽
			for (int i = 0; i < columnWidth.length; i++) {
				sheet.setColumnWidth(i, columnWidth[i]);
			}
			// 3.1创建第一行
			HSSFRow row = sheet.createRow(0);
			HSSFCell cell = row.createCell(0);
			cell.setCellValue(header);
			
			HSSFRow row0 = sheet.createRow(1);
			cell.setCellStyle(style);
			// 将列名写入
			for (int i = 0; i < titel.length; i++) {
				// 给列写入数据,创建单元格,写入数据
				cell = row0.createCell(i);
				cell.setCellStyle(style);
				cell.setCellValue(titel[i]);
			}
			// 写入正式数据
			int num=0;
			for (int i = sum*count; i < list.size(); i++) {
				Map rw = (Map) list.get(i);
				HSSFRow row2 = sheet.createRow(num%sum+2);
				num++;
				for (int j = 0; j < columnName.length; j++) {
					cell = row2.createCell(j);
					obj=rw.get(columnName[j]);
					obj=obj==null?"":obj;
					cell.setCellValue(obj.toString());
					cell.setCellStyle(style);
				}
				
				if(i==sum*(count+1)-1) {
					break;
				}
			}
			count++;
		}
		return wb;
	}

}

项目启动后直接访问http://localhost:8080/downExcel
效果预览
在这里插入图片描述
实际中的数据应该从数据库中查询出来的,这只是一个小demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值