package com.huachan.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.disk.DiskFileItem;
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.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
/**
* 对excel进行读取输出
*
* @author 闵渭凯 2018年5月9日
*/
public class ExcelUtil {
// --------------------start------------------------将excel文件转为List--------------------start-----------------
private int totalRows = 0;
private int totalCells = 0;
private String errorMsg;
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
/**
* 读EXCEL文件
*
* @param fielName
* @return
*/
public List<Map<Object, Object>> getExcelInfo(String fileName, MultipartFile Mfile) {
// 把spring文件上传的MultipartFile转换成File
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile;
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File file = fi.getStoreLocation();
List<Map<Object, Object>> userList = new ArrayList<>();
InputStream is = null;
try {
// 验证文件名是否合格
if (!validateExcel(fileName)) {
return null;
}
// 判断文件时2003版本还是2007版本
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(fileName)) {
isExcel2003 = false;
}
is = new FileInputStream(file);
userList = getExcelInfo(is, isExcel2003);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
return userList;
}
/**
* 此方法两个参数InputStream是字节流。isExcel2003是excel是2003还是2007版本
*
* @param is
* @param isExcel2003
* @return
* @throws IOException
*/
public List<Map<Object, Object>> getExcelInfo(InputStream is, boolean isExcel2003) {
List<Map<Object, Object>> userList = null;
try {
Workbook wb = null;
// 当excel是2003时
if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
userList = readExcelValue(wb);
} catch (IOException e) {
e.printStackTrace();
}
return userList;
}
/**
* 读取Excel里面的信息
*
* @param wb
* @return
*/
private List<Map<Object, Object>> readExcelValue(Workbook wb) {
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
this.totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数)
if (totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<Map<Object, Object>> userList = new ArrayList<>();
Map<Object, Object> list = null;
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null)
continue;
list = new HashMap<>();
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
try {
if (null != cell) {
list.put(c, getCellValue(wb, cell));
}
} catch (Exception e) {
continue;
}
}
userList.add(list);
}
return userList;
}
private static Object getCellValue(Workbook wb, Cell cell) {
Object columnValue = null;
if (cell != null) {
DecimalFormat df = new DecimalFormat("0");// 格式化 number
// String
// 字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("#");// 格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
columnValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if ("@".equals(cell.getCellStyle().getDataFormatString())) {
columnValue = df.format(cell.getNumericCellValue());
} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
columnValue = nf.format(cell.getNumericCellValue());
} else {
columnValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
}
break;
case Cell.CELL_TYPE_BOOLEAN:
columnValue = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
columnValue = "";
break;
case Cell.CELL_TYPE_FORMULA:
// 格式单元格
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateFormulaCell(cell);
CellValue cellValue = evaluator.evaluate(cell);
columnValue = cellValue.getNumberValue();
break;
default:
columnValue = cell.toString();
}
}
return columnValue;
}
public ExcelUtil() {
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getTotalCells() {
return totalCells;
}
public void setTotalCells(int totalCells) {
this.totalCells = totalCells;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
// --------------------end------------------------将excel文件转为List--------------------end-----------------
// --------------------start------------------------将list转为excel文件--------------------start-----------------
HttpServletResponse response;
// 文件名
private String fileName;
// 文件保存路径
private String fileDir;
// sheet名
private String sheetName;
// 表头字体
private String titleFontType = "Arial Unicode MS";
// 表头背景色
private String titleBackColor = "C1FBEE";
// 表头字号
private short titleFontSize = 12;
// 添加自动筛选的列 如 A:M
private String address = "";
// 正文字体
private String contentFontType = "Arial Unicode MS";
// 正文字号
private short contentFontSize = 12;
// Float类型数据小数位
private String floatDecimal = ".00";
// Double类型数据小数位
private String doubleDecimal = ".00";
// 设置列的公式
private String colFormula[] = null;
DecimalFormat floatDecimalFormat = new DecimalFormat(floatDecimal);
DecimalFormat doubleDecimalFormat = new DecimalFormat(doubleDecimal);
private HSSFWorkbook workbook = null;
public ExcelUtil(String fileDir, String sheetName) {
this.fileDir = fileDir;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
public ExcelUtil(HttpServletResponse response, String fileName, String sheetName) {
this.response = response;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
/**
* 设置表头字体.
*
* @param titleFontType
*/
public void setTitleFontType(String titleFontType) {
this.titleFontType = titleFontType;
}
/**
* 设置表头背景色.
*
* @param titleBackColor
* 十六进制
*/
public void setTitleBackColor(String titleBackColor) {
this.titleBackColor = titleBackColor;
}
/**
* 设置表头字体大小.
*
* @param titleFontSize
*/
public void setTitleFontSize(short titleFontSize) {
this.titleFontSize = titleFontSize;
}
/**
* 设置表头自动筛选栏位,如A:AC.
*
* @param address
*/
public void setAddress(String address) {
this.address = address;
}
/**
* 设置正文字体.
*
* @param contentFontType
*/
public void setContentFontType(String contentFontType) {
this.contentFontType = contentFontType;
}
/**
* 设置正文字号.
*
* @param contentFontSize
*/
public void setContentFontSize(short contentFontSize) {
this.contentFontSize = contentFontSize;
}
/**
* 设置float类型数据小数位 默认.00
*
* @param doubleDecimal
* 如 ".00"
*/
public void setDoubleDecimal(String doubleDecimal) {
this.doubleDecimal = doubleDecimal;
}
/**
* 设置doubel类型数据小数位 默认.00
*
* @param floatDecimalFormat
* 如 ".00
*/
public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
this.floatDecimalFormat = floatDecimalFormat;
}
/**
* 设置列的公式
*
* @param colFormula
* 存储i-1列的公式 涉及到的行号使用@替换 如A@+B@
*/
public void setColFormula(String[] colFormula) {
this.colFormula = colFormula;
}
/**
* 写excel.
*
* @param titleColumn
* 对应bean的属性名
* @param titleName
* excel要导出的表名
* @param titleSize
* 列宽
* @param dataList
* 数据
*/
public void wirteExcel(String titleColumn[], String titleName[], int titleSize[], List<?> dataList) {
// 添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
Sheet sheet = workbook.createSheet(this.sheetName);
// 新建文件
OutputStream out = null;
try {
if (fileDir != null) {
// 有文件路径
out = new FileOutputStream(fileDir);
} else {
// 否则,直接写到输出流中
out = response.getOutputStream();
fileName = fileName + ".xls";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition",
"attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
}
// 写入excel的表头
Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
// 设置样式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short) 10);
for (int i = 0; i < titleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); // 设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellStyle(titleStyle);
cell.setCellValue(titleName[i].toString());
}
// 为表头添加自动筛选
if (!"".equals(address)) {
CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
sheet.setAutoFilter(c);
}
// 通过反射获取数据并写入到excel中
if (dataList != null && dataList.size() > 0) {
// 设置样式
HSSFCellStyle dataStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize);
if (titleColumn.length > 0) {
for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
Object obj = dataList.get(rowIndex - 1); // 获得该对象
Class clsss = obj.getClass(); // 获得该对对象的class实例
Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].toString().trim();
if (!"".equals(title)) { // 字段不为空
// 使首字母大写
String UTitle = Character.toUpperCase(title.charAt(0))
+ title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get" + UTitle;
// 设置要执行的方法
Method method = clsss.getDeclaredMethod(methodName);
// 获取返回类型
String returnType = method.getReturnType().getName();
String data = method.invoke(obj) == null ? "" : method.invoke(obj).toString();
Cell cell = dataRow.createCell(columnIndex);
if (data != null && !"".equals(data)) {
if ("int".equals(returnType)) {
cell.setCellValue(Integer.parseInt(data));
} else if ("long".equals(returnType)) {
cell.setCellValue(Long.parseLong(data));
} else if ("float".equals(returnType)) {
cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
} else if ("double".equals(returnType)) {
cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
} else {
cell.setCellValue(data);
}
}
} else { // 字段为空 检查该列是否是公式
if (colFormula != null) {
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex + 1) + "");
Cell cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf.toString());
}
}
}
}
}
}
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 将16进制的颜色代码写入样式中来设置颜色
*
* @param style
* 保证style统一
* @param color
* 颜色:66FFDD
* @param index
* 索引 8-64 使用时不可重复
* @return
*/
public CellStyle setColor(CellStyle style, String color, short index) {
if (color != "" && color != null) {
// 转为RGB码
int r = Integer.parseInt((color.substring(0, 2)), 16); // 转为16进制
int g = Integer.parseInt((color.substring(2, 4)), 16);
int b = Integer.parseInt((color.substring(4, 6)), 16);
// 自定义cell颜色
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short) index, (byte) r, (byte) g, (byte) b);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(index);
}
return style;
}
/**
* 设置字体并加外边框
*
* @param style
* 样式
* @param style
* 字体名
* @param style
* 大小
* @return
*/
public CellStyle setFontAndBorder(CellStyle style, String fontName, short size) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(size);
font.setFontName(fontName);
// font.setBoldweight(true);
style.setFont(font);
style.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
style.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
style.setBorderTop(CellStyle.BORDER_THIN);// 上边框
style.setBorderRight(CellStyle.BORDER_THIN);// 右边框
return style;
}
/**
* 删除文件
*
* @param fileDir
* @return
*/
public boolean deleteExcel() {
boolean flag = false;
File file = new File(this.fileDir);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
/**
* 删除文件
*
* @param fileDir
* @return
*/
public boolean deleteExcel(String path) {
boolean flag = false;
File file = new File(path);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
/**
* 从服务器上下载PDF
*
* @param fileName
* 文件名
* @param response
*/
public static void downLoad(String newPath, String fileName, HttpServletResponse response) {
try {
FileInputStream fileInputStream = new FileInputStream(newPath + fileName);
ServletOutputStream outputStream = response.getOutputStream();
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("content-type", "application/msexcel");
// 输出
int len = 1;
byte[] bs = new byte[1024];
while ((len = fileInputStream.read(bs)) != -1) {
outputStream.write(bs, 0, len);
}
fileInputStream.close();
} catch (Exception e) {
}
}
// --------------------end------------------------将list转为excel文件--------------------end-----------------
}
/**
*
* 检验EXCEL文件版本
*/
class WDWUtil {
// excel 2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
// excel 2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
解析方法
// 解析excel
ExcelUtil reu = new ExcelUtil();
List<Map<Object, Object>> companyList = reu.getExcelInfo(name, file);
List<String> exist = new ArrayList<>();
导出excel
public Map<String, Object> downloadExcel(String positionId, HttpServletResponse response) {
Map<String, Object> map = new HashMap<>();
try {
// 判断参数是否为空
if (StringUtils.isBlank(positionId)) {
map.put("status", 202);
map.put("message", "参数错误");
return map;
}
List<JobseekerExcel> jbList = joberService.findUserById(positionId);
List<JobseekerExcel> newJbList = FormatDataUtil.getFarmatMap(jbList);
if (jbList.size() > 0) {
// 文件名
String filename = "Jobseeker.xls";
ExcelUtil pee = new ExcelUtil(newExcelPath + filename, "sheet1");
// 调用
String titleColumn[] = { "company_name", "jobtitle", "createtime3", "createtime4", "name", "phone",
"email", "gender1", "age", "location", "education1", "jobyear" };
String titleName[] = { "企业", "职位", "职位添加时间", "候选人添加时间", "姓名", "手机号码", "电子邮箱", "性别", "年龄", "所在地", "学历",
"工作年限" };
int titleSize[] = { 25, 13, 18, 18, 13, 18, 18, 13, 13, 13, 13, 13 };
pee.wirteExcel(titleColumn, titleName, titleSize, newJbList);
// 响应给浏览器提供下载
ExcelUtil.downLoad(newExcelPath, filename, response);
map.put("status", 200);
map.put("message", "候选人导出成功");
} else {
map.put("status", 204);
map.put("message", "该职位暂无候选人");
}
} catch (Exception e) {
map.put("status", 500);
map.put("message", "导出异常");
}