package com.zhiwei.readWechat;

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

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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;

import com.zw.entity.ReadWechat;

/**
 * 获取地址输入excel
 * 
 * @author Administrator
 *
 */
public class ReadExcel {

	/**
	 * 获取一组
	 * 
	 * @param url
	 * @return
	 */
	public static List<ReadWechat> getExcel(String url) {
		InputStream in = null;
		try {
			in = new FileInputStream(new File(url));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		List<ReadWechat> list = new ArrayList<>();
		Workbook book = null;
		try {
			book = getExcelWorkbook(in);
		} 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;
				try {
					ReadWechat rw = new ReadWechat();
					for (int j = 0; j < lastCellNum; j++) {
						cell = row.getCell(j);
						if (cell != null) {
							// String str = cell.getStringCellValue();
							if (sheet.getRow(0).getCell(j).getStringCellValue().equals("地址")) {
								rw.setUrl(cell.getStringCellValue());
							}
							if (sheet.getRow(0).getCell(j).getStringCellValue().equals("标题")) {
								rw.setTitle(cell.getStringCellValue());
							}
							if (sheet.getRow(0).getCell(j).getStringCellValue().equals("来源")) {
								rw.setSource(cell.getStringCellValue());
							}
						}
					}
					if (rw != null && rw.getUrl() != null && rw.getUrl().length() > 10)
						list.add(rw);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		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(InputStream in) throws IOException {
		Workbook book = null;
		try {
			book = WorkbookFactory.create(in);
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		}
		return book;
	}

}
