package com.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
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.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class OfficeUtil {

	/********************************************************* xls *************************************************************/

	/**
	 * 写Excel并下载针对.xls
	 * 
	 */
	public boolean writeAndDownExcelToXLS(HttpServletRequest request,HttpServletResponse response, List list, String[] titles,
			HSSFWorkbook workbook, HSSFSheet sheet, String filepath) {
		boolean flag = true;
		if (null!=list && list.size()>0) {
			try {
				for (int i = 0; i < titles.length; i++) {
					HSSFRow row = sheet.createRow(i);
					WriteExcelCellContextToXLS(workbook, row,i,titles[i]);
				}
				for (int j = 1; j <= list.size(); j++) {
					Object[] object = object = (Object[]) list.get(j - 1);
					HSSFRow row = sheet.createRow(j);
					for (int n = 0; n < object.length; n++) {
						WriteExcelCellContextToXLS(workbook,row,n,object[n] == null ? "" : UtilTools.delHTMLTag(object[n].toString()));
					}
				}
				flag = CreateExcel(filepath, workbook);
				if (flag) {
					flag = UtilTools.downFile(response, filepath);
				}
			} catch (Exception e) {
				flag = false;
				e.printStackTrace();
			}
		}
		return flag;
	}

	/**
	 * 写Excel内容针对.xls且对标题行加样式
	 * 
	 */
	public static void WriteExcelCellContextToXLS(HSSFWorkbook workbook,HSSFRow row,int cellindex,String content) {
		HSSFCell cell = row.createCell((short) cellindex);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(content);
		//加样式
		HSSFCellStyle style = workbook.createCellStyle();
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 11);// 字号
		font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);// 加粗
		font.setColor(HSSFFont.COLOR_RED);// 颜色
		style.setFont(font);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		cell.setCellStyle(style);
	}
	
	/**
	 * 写Excel内容针对.xls
	 * 
	 */
	public static void WriteExcelCellContextToXLS(HSSFRow row,int cellindex,String content) {
		HSSFCell cell = row.createCell((short) cellindex);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(content);
	}

	/**
	 * 获取.xls Excel单元格的值
	 * 
	 */
	public static Object getCellResultToXLS(HSSFRow row, int cellnum) {
		HSSFCell cell = row.getCell((short) cellnum);
		Object value = null;
		DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
		DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字
		if (null != cell) {
			switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case HSSFCell.CELL_TYPE_FORMULA:
				try {
					value=cell.getNumericCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					value =""; 
				}
				break;
			case HSSFCell.CELL_TYPE_NUMERIC:
				/*if ("@".equals(cell.getCellStyle().getDataFormat())) {
					value = df.format(cell.getNumericCellValue());
				} else if ("General".equals(cell.getCellStyle().getDataFormat())) {
					value = nf.format(cell.getNumericCellValue());
				} else {
					value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
				}*/
				if (HSSFDateUtil.isCellDateFormatted(cell)) {  //日期   
			        value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));   
			    } else { // 纯数字     
				    value = df.format(cell.getNumericCellValue()); 
				}  
				break;
			case HSSFCell.CELL_TYPE_BOOLEAN:
				value = cell.getBooleanCellValue();
				break;
			case HSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			default:
				value = cell.toString();
			}
		} else {
			value = "";
		}

		return value;

	}

	/********************************************************* xlsx *************************************************************/

	/**
	 * 写Excel内容针对.xlsx且对标题行加样式
	 * 
	 */
	public static void WriteExcelCellContextToXLSX(XSSFWorkbook workbook,XSSFRow row,int cellindex,String content) {
		XSSFCell cell = row.createCell(cellindex);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		cell.setCellValue(content);
		//加样式
		XSSFCellStyle style = workbook.createCellStyle();
		XSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		font.setColor(HSSFFont.COLOR_RED);
		style.setFont(font);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		cell.setCellStyle(style);
	}
	
	/**
	 * 写Excel内容针对.xlsx
	 * 
	 */
	public static void WriteExcelCellContextToXLSX(XSSFRow row, int cellindex,String content) {
		XSSFCell cell = row.createCell(cellindex);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		cell.setCellValue(content);
	}

	/**
	 * 获取.xlsx Excel单元格的值
	 * 
	 */
	public static Object getExcelResultToXLSX(XSSFRow row, int cellnum) {
		Object value = null;
		XSSFCell cell = row.getCell(cellnum);
		DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
		DecimalFormat ndf = new DecimalFormat("0.00");// 格式化数字
		if (null != cell) {
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_NUMERIC:
				if ("@".equals(cell.getCellStyle().getDataFormatString())) {
					value = df.format(cell.getNumericCellValue());
				} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
					value = ndf.format(cell.getNumericCellValue());
				} else {
					value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
				}
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = cell.getBooleanCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			default:
				value = cell.toString();
			}

		}
		
		if(value==null)value="";
		return value;
	}
	
	/**
	 * 判断sheet行标题与指定标题是否一至
	 */
	public static boolean sheetRowTitleToXlSX(XSSFSheet  sheet,String[] titles){
		 boolean flag=true;
		 XSSFRow row=sheet.getRow(0);
		 for(int i=0;i<titles.length;i++){
			 String rt=getExcelResultToXLSX(row, i).toString();
			 if(!titles[i].equals(rt)){
				 flag=false;
				 break;
			 }
		 }
		 
		 return flag;
	}

	/**************************************************************************************************************/

	/**
	 * 生成Excel
	 * 
	 */
	public static boolean CreateExcel(String filepath, Workbook workbook) {
		boolean flag = true;
		try {
			File file = new File(filepath);
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			OutputStream os = new FileOutputStream(filepath);
			try {
				workbook.write(os);
				os.flush();
				os.close();
			} catch (IOException e) {
				flag = false;
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			flag = false;
			e.printStackTrace();
		}
		return flag;
	}
	
	public static void main(String[] args) throws Exception {
		
		 
	}

}