java poi导出excel文件

1,ExcelReportHandler类

package com.poi.excel;

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

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

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 * 导出excel数据
 * @author Administrator
 *
 */
public abstract class ExcelReportHandler {

	/**
	 * 默认的头部样式
	 */
	protected HSSFCellStyle defaultHeadCellStyle;

	/**
	 * 默认的体部样式
	 */
	protected HSSFCellStyle defaultBodyCellStye;

	protected HSSFFont defaultHeadFont;

	protected HSSFFont defaultBodyFont;

	/**
	 * 导出excel文件
	 * @param response 
	 * @param headTitle 标题列
	 * @param fileName 文件名称
	 * @param list 数据集合
	 * @throws Exception
	 */
	public void exportExcel(HttpServletResponse response, String[] headTitle, String fileName, List list) throws Exception {
		response.reset();
		response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + ".xls\"");// 设置response的Header
		ServletOutputStream out = response.getOutputStream();// 得到输出流
		HSSFWorkbook wb = new HSSFWorkbook();// 实例化工作薄对象
		defaultHeadCellStyle = wb.createCellStyle();
		defaultBodyCellStye = wb.createCellStyle();
		defaultHeadFont = wb.createFont();
		defaultBodyFont = wb.createFont();
		HSSFSheet sheet = wb.createSheet();// 创建sheet
		createHead(sheet, headTitle);// 创建execl头
		createBody(sheet, list);// 创建execl体
		wb.write(out);// 把工作薄写入到输出流
		out.flush();// 刷新流
		out.close();// 关闭流
	}

	/**
	 * 创建标题列
	 * @param sheet
	 * @param headTitle
	 * @throws IOException
	 */
	protected void createHead(HSSFSheet sheet, String[] headTitle) throws IOException {
		Row row = sheet.createRow(0);
		Cell cell = null;
		for (int i = 0; i < headTitle.length; i++) {
			cell = row.createCell((short) i);
			cell.setCellValue(headTitle[i]);
			cell.setCellStyle(getHeadCellStyle());
		}
	}

	/**
	 * 默认的excel头样式
	 * @return
	 */
	protected HSSFCellStyle getHeadCellStyle() {
		defaultHeadCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置居中
		defaultHeadFont.setFontHeightInPoints((short) 13);// 设置字体样式
		defaultHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
		defaultHeadCellStyle.setFont(defaultHeadFont);
		return defaultHeadCellStyle;
	}

	/**
	 * 获取默认的excel体样式
	 * @return
	 */
	protected HSSFCellStyle getBodyCellStyle() {
		defaultBodyCellStye.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置居中
		defaultBodyFont.setFontHeightInPoints((short) 12);// 设置字体样式
		defaultBodyCellStye.setFont(defaultBodyFont);
		return defaultBodyCellStye;
	}

	/**
	 * 导出excel体内容
	 * @param sheet
	 * @param list
	 */
	public abstract void createBody(HSSFSheet sheet, List list);
}






2,ExportUserListExcel类


package com.poi.excel;

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

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 * 导出excel数据
 * @author Administrator
 *
 */
public class ExportUserListExcel extends ExcelReportHandler{

	@Override
	public void createBody(HSSFSheet sheet, List list) {
		Row row = null;
		Cell cell = null;
		Integer rowIndex = 0;
		for (int i = 0; i < list.size(); i++) {
			User user = (User)list.get(i);
			rowIndex ++;
			row = sheet.createRow(rowIndex);  //创建行
			cell = row.createCell((short) 0);  	    //创建单元格
			cell.setCellValue(i+1);
			cell.setCellStyle(getBodyCellStyle());
		
			cell = row.createCell((short) 1);
			cell.setCellValue(user.getName());
			cell.setCellStyle(getBodyCellStyle());
			
			cell = row.createCell((short) 2);
			cell.setCellValue(user.getEmail());
			cell.setCellStyle(getBodyCellStyle());
			
			cell = row.createCell((short) 3);
			cell.setCellValue(user.getPhone());
			cell.setCellStyle(getBodyCellStyle());
			
			cell = row.createCell((short) 4);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			cell.setCellValue(sdf.format(new Date()));
			cell.setCellStyle(getBodyCellStyle());
		}
	}

}




3,ExcelControler类


package com.poi.excel;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ExcelControler
 */
@WebServlet("/ExcelControler")
public class ExcelControler extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExcelControler() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			List<User> list = new ArrayList<User>();
			User user = null;
			for(int i=0;i<100;i++){
				user = new User();
				user.setId(i);
				user.setAddress("中国广东深圳宝安区");
				user.setName("护腕"+i);
				user.setEmail("sldhflksj@dd.com.cn");
				user.setPhone("125859067906798"+i);
				user.setSex((i%2==0? "男" : "女"));
				list.add(user);
			}
			ExportUserListExcel execl = new ExportUserListExcel();
			execl.exportExcel(response,new String[] {"序号","名称","邮箱","电话","时间"},"user list",list);
		} catch (Exception e) {
			response.getWriter().print("导出excel有误!");
		}
	}

}



第三个类为servlet,导入项目之后直接调用:http://localhost:8080/demo/ExcelControler


请自行下载POI  jar包 本项目中用的是: poi-3.9.jar
















  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个完整的 Java POI 导出 Excel 文件并下载的示例代码: ```java import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExportUtil { public static void export(HttpServletResponse response) throws IOException { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 添加表头行 Row headerRow = sheet.createRow(0); Cell headerCell1 = headerRow.createCell(0); headerCell1.setCellValue("Name"); Cell headerCell2 = headerRow.createCell(1); headerCell2.setCellValue("Age"); // 添加数据行 List<Person> personList = getPersonList(); for (int i = 0; i < personList.size(); i++) { Person person = personList.get(i); Row row = sheet.createRow(i + 1); Cell cell1 = row.createCell(0); cell1.setCellValue(person.getName()); Cell cell2 = row.createCell(1); cell2.setCellValue(person.getAge()); } // 设置响应头,告诉浏览器下载文件 response.setHeader("Content-Disposition", "attachment;filename=example.xlsx"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 将工作簿写入响应输出流 workbook.write(response.getOutputStream()); // 关闭工作簿 workbook.close(); } private static List<Person> getPersonList() { List<Person> personList = new ArrayList<>(); personList.add(new Person("Alice", 20)); personList.add(new Person("Bob", 25)); personList.add(new Person("Charlie", 30)); return personList; } private static class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } } ``` 这段代码定义了一个名为 `ExcelExportUtil` 的类,其中包含了一个名为 `export` 的静态方法,用于导出 Excel 文件并下载。在 `export` 方法中,首先创建了一个工作簿对象 `workbook`,然后创建了一个工作表对象 `sheet`,并向其中添加了表头行和数据行。最后将工作簿写入响应输出流,并设置响应头,告诉浏览器下载文件。 在 `getPersonList` 方法中,定义了一个名为 `Person` 的内部类,用于存储人员信息。在示例代码中,生成了一个包含三个人员信息的列表。 如果需要调用上述代码,可以在 Servlet 或者 Spring MVC 的控制器中使用以下代码: ```java @RequestMapping("/download") public void download(HttpServletResponse response) throws IOException { ExcelExportUtil.export(response); } ``` 其中 `"/download"` 是一个映射到下载方法的 URL。这段代码会调用 `ExcelExportUtil` 类的静态方法 `export`,并将响应对象 `response` 传递给它。需要注意的是,需要将 `HttpServletResponse` 对象作为参数传递给 `export` 方法,以便将 Excel 文件写入响应输出流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值