package com.saga.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * excel工具
 *
 * @author 李井强
 */
public class ExcelUtil {

	/**
	 * 读取excel至缓存
	 */
	public static Map<Integer, Map<Integer, Map<Integer, String>>> readExcel(File file) {
		Map<Integer, Map<Integer, Map<Integer, String>>> result = new HashMap<Integer, Map<Integer, Map<Integer, String>>>();
		try {
			Workbook book = Workbook.getWorkbook(file);
			// System.out.println(book.getNumberOfSheets());
			// 遍历sheet
			for (int k = 0; k < book.getNumberOfSheets(); k++) {
				// excel导入map存储,sheet页/行/列
				result.put(k, new HashMap<Integer, Map<Integer, String>>());
				Sheet sheet = book.getSheet(k);
				// System.out.println("Received:" + sheet.getName());
				int rownum = sheet.getRows();
				int colnum = sheet.getColumns();
				if (rownum != 0) {
					for (int j = 0; j < rownum; j++) {
						result.get(k).put(j, new HashMap<Integer, String>());
						for (int i = 0; i < colnum; i++) {
							Cell cell = sheet.getCell(i, j);
							String content = cell.getContents();
							result.get(k).get(j).put(i, content);
							// System.out.println("(" + i + "," + j + ")=" +
							// content);
						}
					}
				}
			}

		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 读取sheet至缓存
	 */
	public static Map<Integer, Map<Integer, String>> readExcel(File file, String sheetName) {
		Map<Integer, Map<Integer, String>> result = new HashMap<Integer, Map<Integer, String>>();
		try {
			Workbook book = Workbook.getWorkbook(file);

			// excel导入map存储,行/列

			Sheet sheet = book.getSheet(sheetName);
			// System.out.println("Received:" + sheet.getName());
			if (sheet == null) {
				return result;
			}
			int rownum = sheet.getRows();
			int colnum = sheet.getColumns();
			if (rownum != 0) {
				for (int j = 0; j < rownum; j++) {
					result.put(j, new HashMap<Integer, String>());
					for (int i = 0; i < colnum; i++) {
						Cell cell = sheet.getCell(i, j);
						String content = cell.getContents();
						result.get(j).put(i, content);
						// System.out.println("(" + i + "," + j + ")=" +
						// content);
					}
				}
			}
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}

	// public static void main(String args[]) {
	// File file = new File("C:/Users/LJQ/Desktop/config.xls");
	// readExcel(file);
	// // readExcel(file, "opcv1");
	// }
}
