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", "導出異常");
}