package com.zhiwei.util;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
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.usermodel.WorkbookFactory;


/**
 * excel文件读取类
 * 
 * @author Administrator
 *
 */
public class ReadExcel {
	private final static Log log = LogFactory.getLog(ReadExcel.class);

	/**
	 * 噪音词的获取
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public List<String> getExcel(String url) {
		List<String> list = new ArrayList<>();
		Workbook book = null;
		try {
			book = getExcelWorkbook(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Sheet sheet = getSheetByNum(book, 0);
		int lastRowNum = sheet.getLastRowNum();
		for (int i = 1; i <= lastRowNum; i++) {
			Row row = null;
			row = sheet.getRow(i);
			if (row != null) {
				int lastCellNum = row.getLastCellNum();
				Cell cell = null;
				String content = "";
				for (int j = 0; j < lastCellNum; j++) {
					cell = row.getCell(j);
					if (cell != null) {
						String str = cell.getStringCellValue();
						if (str != null) {
							content = str;
							break;
						}
					}
				}
				if (content != null)
					list.add(content);
			}
		}
		return list;
	}

	public static Sheet getSheetByNum(Workbook book, int number) {
		Sheet sheet = null;
		try {
			sheet = book.getSheetAt(number);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
		return sheet;
	}

	public static Workbook getExcelWorkbook(String filePath) throws IOException {
		Workbook book = null;
		File file = null;
		FileInputStream fis = null;
		try {
			file = new File(filePath);
			if (!file.exists()) {
				throw new RuntimeException("文件不存在");
			} else {
				fis = new FileInputStream(file);
				book = WorkbookFactory.create(fis);
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
		return book;
	}

}
