POI 导出Excel工具类

maven依赖


org.apache.poi
poi
RELEASE


org.apache.servicemix.bundles
org.apache.servicemix.bundles.poi
3.9_2


org.apache.poi
poi-ooxml
RELEASE


实现类

package com.fenta.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


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.HSSFRichTextString;
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;


public class ExcelUtil {


	/**
	 * 实体类导出excel
	 * 
	 * @param title
	 *            标题,sheet名称 不能为空
	 * @param headers
	 *            列名 String[] 根据实体定义的字段顺序
	 * @param dataset
	 *            实体类集合
	 * @param out
	 *            输出流
	 */
	@SuppressWarnings({ "resource", "unchecked", "rawtypes" })
	public static void exportEntityExcel(String title, String[] headers, Collection dataset, OutputStream out) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(title);
		// 添加title
		HSSFRow header = sheet.createRow(0);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (headers.length - 1)));
		HSSFCellStyle titleStyle = workbook.createCellStyle();
		header.setHeightInPoints((short) 46);
		HSSFFont titleFont = workbook.createFont();
		titleFont.setFontHeightInPoints((short) 24);
		titleFont.setFontName("微软雅黑");
		titleStyle.setFont(titleFont);
		HSSFCell titleCell = header.createCell(0);
		titleCell.setCellStyle(titleStyle);
		titleCell.setCellValue(title);


		HSSFCellStyle style = workbook.createCellStyle();
		// 自动换行
		style.setWrapText(true);
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setFontName("微软雅黑");
		style.setFont(font);
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setWrapText(true);
		HSSFFont font2 = workbook.createFont();
		font2.setFontName("微软雅黑");
		font2.setFontHeightInPoints((short) 10);
		style2.setFont(font2);


		HSSFRow row = sheet.createRow(1);
		row.setHeightInPoints((short) 32);
		// 添加head 标题列
		for (short i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(style);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
			if (i == 0) {
				sheet.setColumnWidth(0, 8 * 256);
			} else {
				sheet.setColumnWidth(i, 16 * 256);
			}
		}


		Iterator it = dataset.iterator();
		int index = 1;
		while (it.hasNext()) {
			++index;


			row = sheet.createRow(index);
			row.setHeightInPoints((short) 20);
			Object t = (Object) it.next();


			Field[] fields = t.getClass().getDeclaredFields();
			for (short i = 0; i < fields.length; i++) {
				HSSFCell cell = row.createCell(i);
				if (i == 0) {
					HSSFCellStyle styleNum = workbook.createCellStyle();
					cell.setCellStyle(styleNum);
				} else {
					cell.setCellStyle(style2);
				}
				Field field = fields[i];
				String fieldName = field.getName();
				String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				try {
					Class tCls = t.getClass();
					Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
					Object value = getMethod.invoke(t, new Object[] {});
					field.setAccessible(true);
					String textValue = String.valueOf(value);
					if (textValue != null) {
						Pattern p = Pattern.compile("^(\\-|\\+)?\\d+(\\.\\d+)?$");
						Matcher matcher = p.matcher(textValue);
						if (textValue.startsWith("[") && textValue.endsWith("]")) {
							textValue = textValue.substring(1, textValue.length() - 1);
							textValue = textValue.replaceAll(",", "");
						}
						if (matcher.matches()) {
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							HSSFRichTextString richString = new HSSFRichTextString(textValue.trim());
							HSSFFont font3 = workbook.createFont();
							richString.applyFont(font3);
							cell.setCellValue(richString);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 导出实体为Map的集合
	 * 
	 * @param title
	 *            标题
	 * @param header
	 *            标题 与key值顺序对应
	 * @param keys
	 *            map的Key
	 * @param dataset
	 *            数据集合
	 * @param out
	 */
	@SuppressWarnings("resource")
	public static void exportMapExcel(String title, String[] headers, String[] keys, Collection> dataset,
			OutputStream out) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(title);
		// 添加title
		HSSFRow header = sheet.createRow(0);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (headers.length - 1)));
		HSSFCellStyle titleStyle = workbook.createCellStyle();
		header.setHeightInPoints((short) 46);
		HSSFFont titleFont = workbook.createFont();
		titleFont.setFontHeightInPoints((short) 24);
		titleFont.setFontName("微软雅黑");
		titleStyle.setFont(titleFont);
		HSSFCell titleCell = header.createCell(0);
		titleCell.setCellStyle(titleStyle);
		titleCell.setCellValue(title);


		HSSFCellStyle style = workbook.createCellStyle();
		// 自动换行
		style.setWrapText(true);
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setFontName("微软雅黑");
		style.setFont(font);
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setWrapText(true);
		HSSFFont font2 = workbook.createFont();
		font2.setFontName("微软雅黑");
		font2.setFontHeightInPoints((short) 10);
		style2.setFont(font2);


		HSSFRow row = sheet.createRow(1);
		row.setHeightInPoints((short) 32);
		// 添加head 标题列
		for (short i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellStyle(style);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
			if (i == 0) {
				sheet.setColumnWidth(0, 8 * 256);
			} else {
				sheet.setColumnWidth(i, 16 * 256);
			}
		}


		Iterator> it = dataset.iterator();
		int index = 1;
		while (it.hasNext()) {
			++index;
			row = sheet.createRow(index);
			row.setHeightInPoints((short) 20);
			Map t = it.next();
			for (short i = 0; i < keys.length; i++) {
				HSSFCell cell = row.createCell(i);
				if (i == 0) {
					HSSFCellStyle styleNum = workbook.createCellStyle();
					cell.setCellStyle(styleNum);
				} else {
					cell.setCellStyle(style2);
				}
				try {
					String key = keys[i];
					Object value = t.get(key);
					String textValue = String.valueOf(value);
					if (textValue != null) {
						Pattern p = Pattern.compile("^(\\-|\\+)?\\d+(\\.\\d+)?$");
						Matcher matcher = p.matcher(textValue);
						if (textValue.startsWith("[") && textValue.endsWith("]")) {
							textValue = textValue.substring(1, textValue.length() - 1);
							textValue = textValue.replaceAll(",", "");
						}
						if (matcher.matches()) {
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							HSSFRichTextString richString = new HSSFRichTextString(textValue.trim());
							HSSFFont font3 = workbook.createFont();
							richString.applyFont(font3);
							cell.setCellValue(richString);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	public static void main(String[] args) throws FileNotFoundException{
		Collection> maps = new ArrayList>();
		for (int i = 0; i < 10; i++) {
			Map map = new HashMap();
			map.put("name", i + "-" + i);
			map.put("age", i * 10);
			maps.add(map);
		}
		exportMapExcel("map测试", new String[] { "名字", "年龄" }, new String[] { "name", "age" }, maps,
				new FileOutputStream("c:/2.xls"));
	}
}

你可能感兴趣的:(文件读写)