package com.lion.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
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.XSSFWorkbook;

public class ExcelUtil {
	/**
	 * 方法描述 根据文件后缀，自适应上传文件的版本
	 * 
	 * @author cpf
	 * @since 2019年7月12日
	 * @param inStr
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static Workbook getWorkbook(InputStream inStr, String fileName) {
		Workbook wb = null;
		try {
			String fileType = fileName.substring(fileName.lastIndexOf("."));
			if (fileType.equals(".xls")) {
				wb = new HSSFWorkbook(inStr); // 2003-
			} else if (fileType.equals(".xlsx")) {
				wb = new XSSFWorkbook(inStr); // 2007+
			} else {
				wb = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			wb = null;
		}
		return wb;
	}
	/**
	 * 方法描述 导出excel
	 * 
	 * @author dlm
	 * @since 2019年3月13日
	 * @param title
	 *            表格每列对应的标题，如：[姓名，电话]
	 * @param value
	 *            表格每列对应的值：如[name,phone]
	 * @param listData
	 *            表格数据
	 * @return
	 */
	public static String exportExcel(String[] title, String[] value, List<Map<String, Object>> listData,
			String sheetName, HttpServletRequest req) {
		String fileName = TimeUtil.getNowTimeTwo() + ".xls";
		String path = req.getSession().getServletContext().getRealPath("/");
		String filePath = "fileUpload/excelexport/";
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(sheetName);// 新建sheet并设置名称
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = null;
		for (int i = 0; i < title.length; i++) {// 创建标题
			sheet.setColumnWidth(i, 20 * 256);
			cell = row.createCell(i);
			cell.setCellValue(title[i]);
		}
		for (int i = 0; i < listData.size(); i++) {// 写数据
			Map<String, Object> map = listData.get(i);
			HSSFCellStyle contextstyle =workbook.createCellStyle();
			row = sheet.createRow(i + 1);
			for (int j = 0; j < value.length; j++) {
				cell = row.createCell(j);
				String cellvalue = map.get(value[j]) == null ? "" : map.get(value[j]).toString();
				if(cellvalue.matches("^(-?\\d+)(\\.\\d+)?$")){
					if(cellvalue.matches("^[-\\+]?[\\d]*$")){
						contextstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#0"));//数据格式只显示整数
						 cell.setCellStyle(contextstyle);
						 cell.setCellValue(Long.parseLong(cellvalue));
					}else{
						contextstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#0.00"));//保留两位小数点
						 cell.setCellStyle(contextstyle);
						cell.setCellValue(Double.parseDouble(cellvalue));
					}
				
					
				}else{
					cell.setCellValue(cellvalue);
				}
			}
		}
		try {
			File file = new File(path + filePath + fileName);
			FileOutputStream out = null;
			out = new FileOutputStream(file);
			workbook.write(out);
			if (out != null) {
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return filePath + fileName;
	}
	/** excel转pdf 校验水印
	 * @param inPath
	 * @param outPath
	 * @return
	 */
	public static boolean getLicenseExcel() {
	  	boolean result = false;
	      try {
	    	  String path=WordUtil.class.getClassLoader().getResource("").toURI().getPath()+ "license.xml";
	          InputStream is = new FileInputStream(new File(path)); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
	          com.aspose.cells.License aposeLic = new com.aspose.cells.License();
	          aposeLic.setLicense(is);
	          result = true;
	          if(is!=null){
	        	  is.close();
	          }
	      } catch (Exception e) {
	      	e.printStackTrace();
	      }
	      return result;
	  }
	/** excel转pdf 支持03和07版本
	 * @param inPath  excel地址
	 * @param outPath  pdf地址
	 * @return
	 */
	public static boolean excel2pdf(String inPath, String outPath) {
		if (!getLicenseExcel()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
	          return false;
	      }
	      try {
	          File file = new File(outPath); // 新建一个空白pdf文档
	          FileOutputStream os = new FileOutputStream(file);
	          com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(inPath);// 原始excel路径
	          wb.save(os, com.aspose.cells.SaveFormat.PDF);
	          os.close();
	      } catch (Exception e) {
	          e.printStackTrace();
	          return false;
	      }
	      return true;
	}
}
