工具方法:java导出Excel表格(简单示例)

1.导入以下jar包(excel工具类和支持的包)http://blog.csdn.net/szwangdf/article/details/39053859

2.ExcelUtil类 (工具类)

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

public class ExcelUtil<T> {
	//exportExcel.java     Myview.java 879行
		public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
			// 声明一个工作薄
			SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
			// 生成一个表格
			SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(title);
			// 设置表格默认列宽度为15个字节
			sheet.setDefaultColumnWidth((short) 15);
			// 产生表格标题行
			SXSSFRow row = (SXSSFRow) sheet.createRow(0);
			for (short i = 0; i < headers.length; i++) {
				SXSSFCell cell = (SXSSFCell) row.createCell(i);
				cell.setCellValue(headers[i]);
			}
			// 遍历集合数据,产生数据行
			Iterator<T> it = dataset.iterator();
			int index = 0;
			while (it.hasNext()) {
				index++;
				row = (SXSSFRow) sheet.createRow(index);
				T t = (T) it.next();
				// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
				Field[] fields = t.getClass().getDeclaredFields();
				for (short i = 0; i < fields.length; i++) {
					SXSSFCell cell = (SXSSFCell) row.createCell(i);
					Field field = fields[i];
					String fieldName = field.getName();
					String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
					try {
						Class<? extends Object> tclass = t.getClass();
						Method getMethod = tclass.getMethod(getMethodName,new Class[] {});
						Object value = getMethod.invoke(t, new Object[] {});
						String textValue = null;
						if (value instanceof Date) {
							Date date = (Date) value;
							SimpleDateFormat sdf = new SimpleDateFormat(pattern);
							textValue = sdf.format(date);
							row.setHeightInPoints(20);
						} else {
							// 其它数据类型都当作字符串简单处理
							textValue = value!=null?value.toString():"";
							row.setHeightInPoints(20);
						}
						// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
						if (textValue != null) {
							Pattern p = Pattern.compile("^//d+(//.//d+)?$");
							Matcher matcher = p.matcher(textValue);
							if (matcher.matches()) {
								// 是数字当作double处理
								cell.setCellValue(Double.parseDouble(textValue));
							} else {
								cell.setCellValue(textValue);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						// 清理资源
					}
				}
			}
			try {
				workbook.write(out);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
}

3.UserVO实体类

 

public class UserVO {
	private String name;
	private int grade;
	private int age;
	private String address;
	private String phone;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
}

4.ExportExcelController.java

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

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

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.taray.pojo.UserVO;
import com.taray.util.ExcelUtil;

@Controller
@Scope("prototype")
public class ExportExcelController {
	@RequestMapping("export")
	public void exportInof(HttpServletRequest request,HttpServletResponse response) throws Exception{
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment; filename=EXCELNAME.xls");
		OutputStream out = response.getOutputStream();
		ExcelUtil<UserVO> t=new ExcelUtil<UserVO>();
		String [] headers={"姓名","年级","年龄","地址","电话"};
		//数据集合开始
		List<UserVO> list=new ArrayList<UserVO>();
		UserVO u1=new UserVO();
		u1.setName("张三");
		u1.setGrade(3);
		u1.setAge(12);
		u1.setAddress("湖中");
		u1.setPhone("123321321");
		UserVO u2=new UserVO();
		u2.setName("李四");
		u2.setGrade(2);
		u2.setAge(16);
		u2.setAddress("湖北");
		u2.setPhone("54324231");
		UserVO u3=new UserVO();
		u3.setName("王五");
		u3.setGrade(4);
		u3.setAge(13);
		u3.setAddress("湖南");
		u3.setPhone("125435342");
		list.add(u1);
		list.add(u2);
		list.add(u3);
		//数据集合结束
		t.exportExcel("文件名词", headers, list, out, "yyyy-MM-dd HH:mm:ss");
		out.close();
	}
}

参考链接:http://blog.csdn.net/xuanzhangran/article/details/54709221

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值