1. 程式人生 > >excel 匯入匯出 poi工具類

excel 匯入匯出 poi工具類

package com.poi;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

/**
 * <pre>
 *   Title: ExcelEntity.java
 *   Description: 
 *   Copyright: Maple Copyright (c) 2013
 *   Company: 
 * </pre>
 * 
 * @author duanke
 * @version 1.0
 * @date 2013年12月31日
 */
public class ExcelEntity {
	private String sheetName; // excel 名稱

	private String[] columnNames; // 列名

	private String[] propertyNames; // 屬性名稱

	private String[] cLabels;

	private int rpp = 200;

	private HSSFCellStyle style = null;

	@SuppressWarnings("rawtypes")
	private List resultList;

	public String getSheetName() {
		return sheetName;
	}

	public void setSheetName(String sheetName) {
		this.sheetName = sheetName;
	}

	public String[] getColumnNames() {
		return columnNames;
	}

	public void setColumnNames(String[] columnNames) {
		this.columnNames = columnNames;
	}

	public String[] getPropertyNames() {
		return propertyNames;
	}

	public void setPropertyNames(String[] propertyNames) {
		this.propertyNames = propertyNames;
	}

	public String[] getCLabels() {
		return cLabels;
	}

	public void setCLabels(String[] labels) {
		cLabels = labels;
	}

	public int getRpp() {
		return rpp;
	}

	public void setRpp(int rpp) {
		this.rpp = rpp;
	}

	public HSSFCellStyle getStyle() {
		return style;
	}

	public void setStyle(HSSFCellStyle style) {
		this.style = style;
	}

	@SuppressWarnings("rawtypes")
	public List getResultList() {
		return resultList;
	}

	@SuppressWarnings("rawtypes")
	public void setResultList(List resultList) {
		this.resultList = resultList;
	}
}
package com.poi;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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.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.hssf.util.Region;

/**
 * <pre>
 *   Title: ExportExcelUtil.java
 *   Description: 
 *   Copyright: Maple Copyright (c) 2013
 *   Company: 
 * </pre>
 * 
 * @author duanke
 * @version 1.0
 * @date 2013年12月31日
 */
public class ExportExcelUtil {
	/**
	 * 建立Excel表格
	 * 
	 * @param object
	 * @param outStream
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static void exportExcel(ExcelEntity object, OutputStream outStream) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(object.getSheetName());
		HSSFRow row = sheet.createRow(0);// 建立第一行
		HSSFCell cell = row.createCell(0);// 建立第一行的第一個單元格
		cell.setCellValue("序號");
		String[] colNames = object.getColumnNames();
		String[] propertys = object.getPropertyNames();
		for (int i = 0; i < colNames.length; i++) { // 新增列名,從第一行的第二個單元格開始新增
			row.createCell(i + 1).setCellValue(colNames[i]);
		}
		Iterator it = object.getResultList().iterator();
		int rowNum = 1; // 從第二行開始新增資料
		while (it.hasNext()) {
			Map map = (Map) it.next();
			HSSFRow rw = sheet.createRow(rowNum);
			rw.createCell(0).setCellValue(rowNum); // 新增序號
			rowNum++;
			for (int x = 0; x < propertys.length; x++) {
				String property = propertys[x];
				if (map.containsKey(property)) {
					Object value = map.get(propertys[x]); // 根據屬性名稱得到屬性值
					if (value == null || "null".equalsIgnoreCase(value.toString())) {
						value = "";
					}
					rw.createCell(x + 1).setCellValue(value + "");
				} else {
					rw.createCell(x + 1).setCellValue("");
				}
			}
		}
		try {
			wb.write(outStream);
			outStream.flush();
			outStream.close();
		} catch (IOException e) {
			if (outStream != null) {
				outStream.close();
			}
			e.printStackTrace();
		}
	}

	/**
	 * 匯出Excel
	 * 
	 * @param response
	 * @param list
	 * @param columns
	 * @param propertyNames
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static void exportView(HttpServletResponse response, List<Map> list, String[] columns, String[] propertyNames) throws IOException, UnsupportedEncodingException, Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		ExcelEntity entity = new ExcelEntity();
		entity.setColumnNames(columns);
		entity.setPropertyNames(propertyNames);
		entity.setResultList(list);
		entity.setSheetName(sdf.format(new Date()));

		OutputStream outStream = response.getOutputStream();
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		String fileName = sdf.format(new Date()) + ".xls";
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso8859-1"));
		exportExcel(entity, outStream);
	}

	/**
	 * 建立通用EXCEL頭部
	 * 
	 * @param headString
	 *            頭部顯示的字元
	 * @param colSum
	 *            該報表的列數
	 */
	@SuppressWarnings("deprecation")
	public void createNormalHead(String headString, int colSum, String sheetName) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);
		HSSFRow row = sheet.createRow(0);

		// 設定第一行
		HSSFCell cell = row.createCell(0);
		row.setHeight((short) 400);

		// 定義單元格為字串型別
		cell.setCellType(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(new HSSFRichTextString(headString));

		// 指定合併區域
		sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) colSum));

		HSSFCellStyle cellStyle = wb.createCellStyle();

		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定單元格居中對齊
		cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定單元格垂直居中對齊
		cellStyle.setWrapText(true);// 指定單元格自動換行

		// 設定單元格字型
		HSSFFont font = wb.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setFontName("宋體");
		font.setFontHeight((short) 300);
		cellStyle.setFont(font);

		cell.setCellStyle(cellStyle);
	}
}

package com.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * <pre>
 *   Title: ReadExcel.java
 *   Description: 
 *   Copyright: Maple Copyright (c) 2013
 *   Company: 
 * </pre>
 * 
 * @author duanke
 * @version 1.0
 * @date 2013年12月31日
 */
public class ReadExcel {
	/**
	 * Excel 2003
	 */
	private final static String XLS = "xls";

	/**
	 * Excel 2007
	 */
	private final static String XLSX = "xlsx";

	/**
	 * 由Excel檔案的Sheet匯出至List
	 * 
	 * @param file
	 *            匯入的excel檔案
	 * @param sheetNum
	 *            excel工作空間,一般情況為0
	 * @return
	 */
	public static List<Map<String, Object>> exportListFromExcel(File file, int sheetNum) throws IOException {
		return exportListFromExcel(new FileInputStream(file), FilenameUtils.getExtension(file.getName()), sheetNum);
	}

	/**
	 * 由Excel流的Sheet匯出至List
	 * 
	 * @param is
	 * @param extensionName
	 * @param sheetNum
	 * @return
	 * @throws IOException
	 */
	public static List<Map<String, Object>> exportListFromExcel(InputStream is, String extensionName, int sheetNum) throws IOException {

		Workbook workbook = null;

		if (extensionName.toLowerCase().equals(XLS)) {
			workbook = new HSSFWorkbook(is);
		} else if (extensionName.toLowerCase().equals(XLSX)) {
			workbook = new XSSFWorkbook(is);
		}

		return readCell(workbook, sheetNum);
	}

	/**
	 * 讀取Cell的值
	 * 
	 * @param sheet
	 * @return
	 */
	public static List<Map<String, Object>> readCell(Workbook workbook, int sheetNum) {
		Sheet sheet = workbook.getSheetAt(sheetNum);

		// 解析公式結果
		// FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 遍歷所有行
		// for (Row row : sheet)
		// 除去表頭即第一行
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			Map<String, Object> map = new HashMap<String, Object>();
			// 便利所有列
			for (Cell cell : row) {

				// 獲取單元格的型別
				CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
				String key = cellRef.formatAsString();

				switch (cell.getCellType()) {
				// 字串
				case Cell.CELL_TYPE_STRING:
					map.put(key, cell.getRichStringCellValue().getString());
					break;
				// 數字
				case Cell.CELL_TYPE_NUMERIC:
					if (DateUtil.isCellDateFormatted(cell)) {
						map.put(key, cell.getDateCellValue());
					} else {
						map.put(key, cell.getNumericCellValue());
					}
					break;
				// boolean
				case Cell.CELL_TYPE_BOOLEAN:
					map.put(key, cell.getBooleanCellValue());
					break;
				// 方程式
				case Cell.CELL_TYPE_FORMULA:
					map.put(key, cell.getCellFormula());
					break;
				case Cell.CELL_TYPE_BLANK:
					break;
				case Cell.CELL_TYPE_ERROR:
					break;
				// 空值
				default:
					map.put(key, "");
				}
			}
			list.add(map);
		}
		return list;

	}

	public static void main(String[] args) throws IOException {
//		String paths = "c:\\excel.xlsx";
		String paths = ReadExcel.class.getResource("c:\\excel.xlsx").getFile();
		List<Map<String, Object>> lists = ReadExcel.exportListFromExcel(new File(paths), 0);
		System.out.println(lists);
	}
}

自行測試匯入jar包poi-3.7.jar、poi-ooxml-3.7.jar、poi-ooxml-schemas-3.7.jar、dom4j-1.6.1.jar、commons-io-2.4.jar