1. 程式人生 > >Excel檔案多sheet解析

Excel檔案多sheet解析

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.xssf.usermodel.XSSFCell;
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.Repository;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author lemon
 * @version 建立時間:2018年10月12日 下午12:49:36 Excel檔案格式解析成JSONArray
 */
@Repository
public class ExcelFileParseToJsonArray {
	private static final String XLSX = ".xlsx";
	private static final String XLS = ".xls";
	private static final Integer INITDATA = 1000;

	/**
	 * 讀取XLSX字尾檔案檔案
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public JSONArray readXlsxExcel(String filePath) throws Exception {
		// 儲存解析後的資料
		Map<Integer, String> map = new HashMap<Integer, String>(INITDATA);
		JSONArray array = new JSONArray();
		String extString = filePath.substring(filePath.lastIndexOf("."));
		InputStream inputStream = new FileInputStream(filePath);
		if (XLSX.equals(extString)) {
			XSSFWorkbook book = new XSSFWorkbook(inputStream);
			// 遍歷多個sheet進行解析
			for (int i = 0; i < book.getNumberOfSheets(); i++) {
				XSSFSheet sheet = book.getSheetAt(i);
				if (sheet != null) {
					// 第一行
					XSSFRow firstRow = sheet.getRow(0);
					int firstLength = firstRow.getLastCellNum();
					for (int k = 0; k < firstLength; k++) {
						map.put(k, firstRow.getCell(k).toString());
					}
					// 行數
					int endRownum = sheet.getLastRowNum() + 1;
					for (int j = 1; j < endRownum; j++) {
						JSONObject obj = new JSONObject();
						StringBuffer sb = new StringBuffer();
						XSSFRow row = sheet.getRow(j);
						// 去除空行
						if (row != null) {
							// 獲取每行長度
							int length = row.getLastCellNum();
							if (length > 0) {
								for (int m = 0; m < length; m++) {
									String value = getXlsxValue(row.getCell(m));
									sb.append(value);
									obj.put(map.get(m), value);
								}
							}
						}
						if (sb.toString().length() > 0) {
							array.add(obj);
						}
					}
				}
			}
		}
		return array;
	}

	/**
	 * 解析XLS字尾Excel檔案
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public JSONArray readXlsExcel(String filePath) throws Exception {
		// 儲存解析後的資料
		Map<Integer, String> map = new HashMap<Integer, String>(INITDATA);
		JSONArray array = new JSONArray();
		String extString = filePath.substring(filePath.lastIndexOf("."));
		InputStream inputStream = new FileInputStream(filePath);
		if (XLS.equals(extString)) {
			HSSFWorkbook book = new HSSFWorkbook(inputStream);
			// 遍歷多個sheet進行解析
			for (int i = 0; i < book.getNumberOfSheets(); i++) {
				HSSFSheet sheet = book.getSheetAt(i);
				if (sheet != null) {
					// 第一行
					HSSFRow firstRow = sheet.getRow(0);
					int firstLength = firstRow.getLastCellNum();
					for (int k = 0; k < firstLength; k++) {
						map.put(k, firstRow.getCell(k).toString());
					}
					// 行數
					int endRownum = sheet.getLastRowNum() + 1;
					for (int j = 1; j < endRownum; j++) {
						JSONObject obj = new JSONObject();
						StringBuffer sb = new StringBuffer();
						HSSFRow row = sheet.getRow(j);
						// 去除空行
						if (row != null) {
							// 獲取每行長度
							int length = row.getLastCellNum();
							if (length > 0) {
								for (int m = 0; m < length; m++) {
									String value = getXlsValue(row.getCell(m));
									sb.append(value);
									obj.put(map.get(m), value);
								}
							}
						}
						if (sb.toString().length() > 0) {
							array.add(obj);
						}
					}
				}
			}
		}
		return array;
	}

	/**
	 * Excel檔案字尾為xlsx的單元格式解析
	 * 
	 * @param cell
	 * @return
	 */
	public static String getXlsxValue(XSSFCell cell) {
		if (cell != null) {
			switch (cell.getCellTypeEnum()) {
			case STRING:
				if (cell.getStringCellValue() != null && cell.getStringCellValue().trim().length() != 0) {
					return cell.getStringCellValue().toString().trim();
				} else {
					return "";
				}
			case BOOLEAN:
				return cell.getBooleanCellValue() + "";
			case BLANK:
				return "";
			case NUMERIC:
				String value = "";
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
					break;
				} else {
					value = new DecimalFormat("0").format(cell.getNumericCellValue());
				}
				return value;
			case FORMULA:
				return cell.getStringCellValue().toString();
			case ERROR:
				return "";
			default:
				return "unkonw";
			}
		} else {
			return "";
		}
		return "";
	}

	/**
	 * Excel格式檔案字尾為xls檔案單元格
	 * 
	 * @param hssfCell
	 * @return
	 */
	public static String getXlsValue(HSSFCell hssfCell) {
		if (hssfCell != null) {
			switch (hssfCell.getCellTypeEnum()) {
			case STRING:
				if (hssfCell.getStringCellValue() != null && hssfCell.getStringCellValue().trim().length() != 0) {
					return hssfCell.getStringCellValue().toString().trim();
				} else {
					return "";
				}
			case BOOLEAN:
				return hssfCell.getBooleanCellValue() + "";
			case BLANK:
				return "";
			case NUMERIC:
				String value = "";
				if (HSSFDateUtil.isCellDateFormatted(hssfCell)) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					value = sdf.format(HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue())).toString();
					break;
				} else {
					value = new DecimalFormat("0").format(hssfCell.getNumericCellValue());
				}
				return value;
			case FORMULA:
				return hssfCell.getStringCellValue().toString();
			case ERROR:
				return "";
			default:
				return "unkonw";
			}
		} else {
			return "";
		}
		return "";
	}
}