excel 导入导出 utils
poi的pom导入
org.apache.poi
poi
3.12
org.apache.poi
poi-ooxml
3.12
com.alibaba
fastjson
1.2.6
utils编写
package com.example.utils;
import org.apache.poi.EncryptedDocumentException;
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.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
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.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("deprecation")
public class ExcelUtils {
/** Excel 最大行数 */
public static final Integer EXCEL_MAX_ROW = 60000;
private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
/**
* 导出excel
*
* @param response
* @param excelHead
* 顶部标题
* @param excelBody
* 数据源字段
* @param dataList
* 数据源
* @param FileName
* 文明名称
* @param SheetName
* sheet页名称
* @return
*/
@SuppressWarnings("resource")
public static void exportExcelByMap(HttpServletResponse response, List excelHead, List excelBody,
List> dataList, String FileName, String SheetName) {
try {
// 文件名称
String folder = "tempexportexcel" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date());
String location = Thread.currentThread().getContextClassLoader().getResource("").getPath();// 获取路径
// 创建文件
File f = new File(location.substring(0, location.indexOf("classes")) + folder);
if (!f.exists()) {
Boolean b=f.mkdirs();
if(!b){
throw new RuntimeException("创建目录失败");
}
}
ServletOutputStream out = response.getOutputStream();
response.setHeader("Content-disposition",
"attachment; filename=" + new String(FileName.getBytes("GB2312"), "8859_1") + ".xls");// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
// 建立excel文件
HSSFWorkbook workBook = new HSSFWorkbook();
int totalCount = 0;
if (!CollectionUtils.isEmpty(dataList)) {
totalCount = dataList.size();
}
for (int n = 0; n < (totalCount / EXCEL_MAX_ROW) + 1; n++) {
HSSFSheet sheet;
if (n == 0) {
// 创建一个工作表
sheet = workBook.createSheet(SheetName);
} else {
sheet = workBook.createSheet(SheetName + "(" + n + ")");
}
// 插入文件头
if (excelHead != null && excelHead.size() > 0) {
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < excelHead.size(); i++) {
// 在Label对象的子对象中指明单元格的位置和内容
HSSFCell cell = row.createCell(i);
cell.setCellValue(excelHead.get(i) + "");
}
}
// 插入数据
if (dataList != null && dataList.size() > 0) {
Integer dataLen = dataList.size() - EXCEL_MAX_ROW * n;
if (dataLen > EXCEL_MAX_ROW) {
dataLen = EXCEL_MAX_ROW;
}
for (int i = 0; i < dataLen; i++) {
Map lineData = dataList.get(i + EXCEL_MAX_ROW * n);
Row row = sheet.createRow(i + 1);
for (int j = 0; j < excelBody.size(); j++) {
Cell cell = row.createCell(j);
Object valObj = lineData.get(excelBody.get(j));
if (valObj != null) {
if (valObj instanceof Date) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
cell.setCellValue(format.format(valObj));
}else{
cell.setCellValue(valObj + "");
}
} else {
cell.setCellValue("");
}
}
}
}
}
workBook.write(out);
out.close();
} catch (IOException e) {
logger.error("导出数据异常", e);
throw new RuntimeException(e.getMessage());
}
}
/**
* 导出excel 只生成文件流,不导出
*
* @param excelHead
* 顶部标题
* @param excelBody
* 数据源字段
* @param dataList
* 数据源
* @param FileName
* 文明名称
* @param SheetName
* sheet页名称
* @return
*/
@SuppressWarnings("resource")
public static InputStream exportExcelByMap(List excelHead, List excelBody,
List> dataList, String FileName, String SheetName) {
try {
// 建立excel文件
HSSFWorkbook workBook = new HSSFWorkbook();
int totalCount = 0;
if (!CollectionUtils.isEmpty(dataList)) {
totalCount = dataList.size();
}
for (int n = 0; n < (totalCount / EXCEL_MAX_ROW) + 1; n++) {
HSSFSheet sheet;
if (n == 0) {
// 创建一个工作表
sheet = workBook.createSheet(SheetName);
} else {
sheet = workBook.createSheet(SheetName + "(" + n + ")");
}
// 插入文件头
if (excelHead != null && excelHead.size() > 0) {
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < excelHead.size(); i++) {
// 在Label对象的子对象中指明单元格的位置和内容
HSSFCell cell = row.createCell(i);
cell.setCellValue(excelHead.get(i) + "");
}
}
// 插入数据
if (dataList != null && dataList.size() > 0) {
Integer dataLen = dataList.size() - EXCEL_MAX_ROW * n;
if (dataLen > EXCEL_MAX_ROW) {
dataLen = EXCEL_MAX_ROW;
}
for (int i = 0; i < dataLen; i++) {
Map lineData = dataList.get(i + EXCEL_MAX_ROW * n);
Row row = sheet.createRow(i + 1);
for (int j = 0; j < excelBody.size(); j++) {
Cell cell = row.createCell(j);
Object valObj = lineData.get(excelBody.get(j));
if (valObj != null) {
cell.setCellValue(valObj + "");
} else {
cell.setCellValue("");
}
}
}
}
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
workBook.write(os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
return is;
} catch (Exception e) {
logger.error("导出数据异常", e);
return null;
}
}
//导出Excel
@SuppressWarnings("resource")
public static void exportExcelByObject(HttpServletResponse response, List excelHead, List excelBody,
List> dataList, String FileName, String SheetName) {
try {
// 文件名称
String folder = "tempexportexcel" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date());
String location = Thread.currentThread().getContextClassLoader().getResource("").getPath();// 获取路径
// 创建文件
File f = new File(location.substring(0, location.indexOf("classes")) + folder);
if (!f.exists()) {
Boolean b = f.mkdirs();
if(!b){
throw new RuntimeException("创建目录失败");
}
}
ServletOutputStream out = response.getOutputStream();
response.setHeader("Content-disposition",
"attachment; filename=" + new String(FileName.getBytes("GB2312"), "iso-8859-1") + ".xls");// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
// 建立excel文件
HSSFWorkbook workBook = new HSSFWorkbook();
int totalCount = 0;
if (!CollectionUtils.isEmpty(dataList)) {
totalCount = dataList.size();
}
for (int n = 0; n < (totalCount / EXCEL_MAX_ROW) + 1; n++) {
HSSFSheet sheet;
if (n == 0) {
// 创建一个工作表
sheet = workBook.createSheet(SheetName);
} else {
sheet = workBook.createSheet(SheetName + "(" + n + ")");
}
// 插入文件头
if (excelHead != null && excelHead.size() > 0) {
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < excelHead.size(); i++) {
// 在Label对象的子对象中指明单元格的位置和内容
HSSFCell cell = row.createCell(i);
cell.setCellValue(excelHead.get(i) + "");
}
}
// 插入数据
if (dataList != null && dataList.size() > 0) {
Integer dataLen = dataList.size() - EXCEL_MAX_ROW * n;
if (dataLen > EXCEL_MAX_ROW) {
dataLen = EXCEL_MAX_ROW;
}
for (int i = 0; i < dataLen; i++) {
Object lineData = dataList.get(i + EXCEL_MAX_ROW * n);
Row row = sheet.createRow(i + 1);
for (int j = 0; j < excelBody.size(); j++) {
Cell cell = row.createCell(j);
Object valObj = getFieldValueByName(excelBody.get(j), lineData);
if (valObj != null) {
String valObjString=valObj.toString();
if (valObj instanceof Boolean) {
if (((Boolean) valObj).booleanValue()) {
cell.setCellValue("是");
}else{
cell.setCellValue("否");
}
} else if (valObj instanceof Date) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
cell.setCellValue(format.format(valObj));
} else if(valObjString.startsWith("http")){
//超链接样式
HSSFCellStyle linkStyle = workBook.createCellStyle();
HSSFFont cellFont= workBook.createFont();
cellFont.setUnderline((byte) 1);
cellFont.setColor(HSSFColor.BLUE.index);
linkStyle.setFont(cellFont);
//塞入超链接参数
cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula("HYPERLINK(\"" + valObj+ "\",\"" + valObj+ "\")");
cell.setCellStyle(linkStyle);
}else {
cell.setCellValue(valObj + "");
}
} else {
cell.setCellValue("");
}
}
}
}
}
workBook.write(out);
out.close();
} catch (IOException e) {
logger.error("导出数据异常", e);
throw new RuntimeException(e.getMessage());
}
}
/**
* 导入excel生成list
*
* @param is
* 文件流
* @param listMapKey
* 键
* @return
*/
public static List> importExcelByMap(InputStream is, List listMapKey) {
List> list = new ArrayList<>();
try {
//修改成支持03格式和07格式
//HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
//XSSFWorkbook wb = new XSSFWorkbook(new POIFSFileSystem(is));
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
for (int i = 1; i <= rowNum; i++) {
Row row = sheet.getRow(i);
Map map = new HashMap<>();
for (int j = 0; j < listMapKey.size(); j++) {
Cell cell = row.getCell(j);
String cellValue = getCellValue(cell);
map.put(listMapKey.get(j) + "", cellValue);
}
list.add(map);
}
} catch (Exception e) {
logger.error("导入excel异常", e);
throw new RuntimeException(e.getMessage());
}
return list;
}
/**
* 导入excel生成list
*
* @param is
* 文件流
* @param
*
* @return
*/
public static List> importExcelByObject(InputStream is, List listKey, String entity) {
List list = new ArrayList();
try {
// 修改成支持03格式和07格式
// HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
// XSSFWorkbook wb = new XSSFWorkbook(new POIFSFileSystem(is));
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
for (int i = 1; i <= rowNum; i++) {
Row row = sheet.getRow(i);
Class> clazz = Class.forName(entity);
Object obj = clazz.newInstance();
for (int j = 0; j < listKey.size(); j++) {
Cell cell = row.getCell(j);
String cellValue = getCellValue(cell);
Field f = clazz.getDeclaredField(listKey.get(j));
f.setAccessible(true);
String type = f.getType().toString();
if ("class java.lang.String".equals(type)) {
f.set(obj, cellValue);
} else if ("class java.lang.Integer".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : Integer.parseInt(cellValue));
} else if ("class java.lang.Long".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : Long.parseLong(cellValue));
} else if ("class java.math.BigDecimal".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : new BigDecimal(cellValue));
} else if ("class java.util.Date".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : formatDate(cellValue));
} else if ("class java.lang.Boolean".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : Boolean.parseBoolean(cellValue));
} else {
f.set(obj, cellValue);
}
}
list.add(obj);
}
} catch (IOException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException | EncryptedDocumentException | InvalidFormatException | ClassNotFoundException
| InstantiationException e) {
logger.error("导入excel异常", e);
throw new RuntimeException(e.getMessage());
}
return list;
}
public static List> importExcelByParam(InputStream is, List> listMapKey) {
List> list = new ArrayList<>();
try {
//HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
for (int i = 1; i <= rowNum; i++) {
Row row = sheet.getRow(i);
Map map = new HashMap<>();
for (int j = 0; j < listMapKey.size(); j++) {
Cell cell = row.getCell(ParseUtils.objToInteger(listMapKey.get(j).get("index")));
String cellValue = getCellValue(cell);
map.put(listMapKey.get(j).get("key") + "", cellValue);
}
list.add(map);
}
} catch (Exception e) {
logger.error("导入excel异常", e);
throw new RuntimeException(e.getMessage());
}
return list;
}
public static List> importExcelObjByParam(InputStream is, List> listMapKey, String entity) {
List list = new ArrayList();
try {
//HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
for (int i = 1; i <= rowNum; i++) {
Row row = sheet.getRow(i);
Class> clazz = Class.forName(entity);
Object obj = clazz.newInstance();
for (int j = 0; j < listMapKey.size(); j++) {
Cell cell = row.getCell(ParseUtils.objToInteger(listMapKey.get(j).get("index")));
String cellValue = getCellValue(cell);
Field f = clazz.getDeclaredField(listMapKey.get(j).get("key").toString());
f.setAccessible(true);
String type = f.getType().toString();
if ("class java.lang.String".equals(type)) {
f.set(obj, cellValue);
} else if ("class java.lang.Integer".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : Integer.parseInt(cellValue));
} else if ("class java.lang.Long".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : Long.parseLong(cellValue));
} else if ("class java.math.BigDecimal".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : new BigDecimal(cellValue));
} else if ("class java.util.Date".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : formatDate(cellValue));
} else if ("class java.lang.Boolean".equals(type)) {
f.set(obj, "".equals(cellValue) ? null : Boolean.parseBoolean(cellValue));
} else {
f.set(obj, cellValue);
}
}
list.add(obj);
}
} catch (Exception e) {
logger.error("导入excel异常", e);
throw new RuntimeException(e.getMessage());
}
return list;
}
/**
* 从excel中抽取数据,key:表头,value:数据
* @param is
* @return
* @throws IOException
*/
public static List> extractFromExcel(InputStream is) throws Exception {
// 数据列表,key:表头,value:数据
List> dataList = new ArrayList<>();
//HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
if (lastRowNum > 0) {
Row titleRow = sheet.getRow(0);
int lastCellNum = titleRow.getLastCellNum();
// 构建表头列表
List titleList = new ArrayList<>(lastCellNum + 1);
for (int j = 0; j <= lastCellNum; j++) {
Cell cell = titleRow.getCell(j);
String cellValue = getCellValue(cell);
titleList.add(cellValue);
}
// 构建表头:数据对应关系
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
Map map = new HashMap<>();
for (int j = 0; j <= lastCellNum; j++) {
Cell cell = row.getCell(j);
String cellValue = getCellValue(cell);
map.put(titleList.get(j) + "", cellValue);
}
dataList.add(map);
}
}
return dataList;
}
public static String getCellValue(Cell cell) {
String cellvalue = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: { // 数值
if (HSSFDateUtil.isCellDateFormatted(cell)) { // 如果是日期格式
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellvalue = sdf.format(date);
} else { // 如果是数字
cell.setCellType(Cell.CELL_TYPE_STRING);
cellvalue = cell.getStringCellValue();
//cellvalue = new BigDecimal(cell.getNumericCellValue()).toPlainString(); //浮点数有精度问题
}
break;
}
case Cell.CELL_TYPE_STRING: { // 字符串
cellvalue = cell.getStringCellValue();
break;
}
case Cell.CELL_TYPE_FORMULA: { // 公式
cellvalue = cell.getCellFormula();
break;
}
case Cell.CELL_TYPE_BLANK: { // 空值
cellvalue = "";
break;
}
case Cell.CELL_TYPE_BOOLEAN: {// Boolean
cellvalue = String.valueOf(cell.getBooleanCellValue());
break;
}
default: { // 默认字符串
cellvalue = cell.getStringCellValue();
break;
}
}
}
return cellvalue.trim();
}
public static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
try {
// todo fixme 这里发现了导出的bug ,目前简单优化了代码
String firstLetter = fieldName.substring(0, 1);
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception ec) {
logger.error(ec.getMessage(), ec);
return null;
}
}
}
/**
* 客户收款分析导出,包含合并单元格,动态列
* @param response
* @param FileName
* @param SheetName
* @param excelHead
* @param exceltitle2
* @param excelBody
* @param dataList
*/
@SuppressWarnings("resource")
public static void exportExcelByMerge(HttpServletResponse response, String FileName, String SheetName,
List> excelHead, List exceltitle2, List excelBody, List> dataList) {
try {
// 文件名称
String folder = "tempexportexcel" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date());
String location = Thread.currentThread().getContextClassLoader().getResource("").getPath();// 获取路径
// 创建文件
File f = new File(location.substring(0, location.indexOf("classes")) + folder);
if (!f.exists()) {
Boolean b = f.mkdirs();
if(!b){
throw new RuntimeException("创建目录失败");
}
}
ServletOutputStream out = response.getOutputStream();
response.setHeader("Content-disposition",
"attachment; filename=" + new String(FileName.getBytes("GB2312"), "8859_1") + ".xls");// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
// 建立excel文件
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFCellStyle cellStyle = workBook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
int totalCount = 0;
if (!CollectionUtils.isEmpty(dataList)) {
totalCount = dataList.size();
}
for (int n = 0; n < (totalCount / EXCEL_MAX_ROW) + 1; n++) {
HSSFSheet sheet;
if (n == 0) {
// 创建一个工作表
sheet = workBook.createSheet(SheetName);
} else {
sheet = workBook.createSheet(SheetName + "(" + n + ")");
}
// 插入文件头
if (excelHead != null && excelHead.size() > 0) {
HSSFRow row00 = sheet.createRow(0);
HSSFRow row01 = sheet.createRow(1);
int cell_i=0;
for (int i = 0; i < excelHead.size(); i++) {
Map title1=excelHead.get(i);
if("2".equals(ParseUtils.objToString(title1.get("row"))) && "1".equals(ParseUtils.objToString(title1.get("cell")))){
sheet.addMergedRegion(new CellRangeAddress(0, 1, (short) cell_i,(short) cell_i));
HSSFCell cell00 = row00.createCell(cell_i);
cell00.setCellStyle(cellStyle);
cell00.setCellValue(ParseUtils.objToString(title1.get("title")));
cell_i++;
}
if("1".equals(ParseUtils.objToString(title1.get("row")))){
Integer result = ParseUtils.objToInteger(title1.get("cell"));
if(result > 0){
int cell_i_2=cell_i+ParseUtils.objToInteger(title1.get("cell"))-1;
HSSFCell cell00 = row00.createCell(cell_i);
cell00.setCellStyle(cellStyle);
sheet.addMergedRegion(new CellRangeAddress(0,0,(short)cell_i,(short)cell_i_2));
cell00.setCellValue(ParseUtils.objToString(title1.get("title")));
cell_i=cell_i_2;
cell_i++;
}
}
}
for (int i = 0; i < exceltitle2.size(); i++) {
HSSFCell cell = row01.createCell(i+8);
cell.setCellStyle(cellStyle);
cell.setCellValue(ParseUtils.objToString(exceltitle2.get(i)));
}
}
// 插入数据
if (dataList != null && dataList.size() > 0) {
Integer dataLen = dataList.size() - EXCEL_MAX_ROW * n;
if (dataLen > EXCEL_MAX_ROW) {
dataLen = EXCEL_MAX_ROW;
}
for (int i = 0; i < dataLen; i++) {
Map lineData = dataList.get(i + EXCEL_MAX_ROW * n);
Row row = sheet.createRow(i + 2);
for (int j = 0; j < excelBody.size(); j++) {
Cell cell = row.createCell(j);
Object valObj = lineData.get(excelBody.get(j));
if (valObj != null) {
cell.setCellValue(valObj + "");
} else {
cell.setCellValue("");
}
}
}
}
}
workBook.write(out);
out.close();
} catch (IOException e) {
logger.error("导出数据异常", e);
throw new RuntimeException(e.getMessage());
}
}
/**
* 导出excel并合并列
*
* @param response
* @param excelHead
* @param excelBody
* @param dataList
* @param FileName
* @param
* @param startRow
* @param endRow
*/
@SuppressWarnings({ "resource"})
public static void exportMergeExcelByObject(HttpServletResponse response, List excelHead, List excelBody,
List> dataList, String FileName, String sheetName, int startRow, int endRow) {
try {
// 文件名称
String folder = "tempexportexcel" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date());
String location = Thread.currentThread().getContextClassLoader().getResource("").getPath();// 获取路径
// 创建文件
File f = new File(location.substring(0, location.indexOf("classes")) + folder);
if (!f.exists()) {
Boolean b = f.mkdirs();
if(!b){
throw new RuntimeException("创建目录失败");
}
}
ServletOutputStream out = response.getOutputStream();
response.setHeader("Content-disposition",
"attachment; filename=" + new String(FileName.getBytes("GB2312"), "8859_1") + ".xlsx");// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
// 建立excel文件
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFCellStyle cellStyle = workBook.createCellStyle();
cellStyle.setWrapText(true);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
XSSFCellStyle cellSt = workBook.createCellStyle();
cellSt.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
cellSt.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellSt.setWrapText(true);
int totalCount = 0;
if (!CollectionUtils.isEmpty(dataList)) {
totalCount = dataList.size();
}
for (int n = 0; n < (totalCount / EXCEL_MAX_ROW) + 1; n++) {
XSSFSheet sheet;
if (n == 0) {
// 创建一个工作表
sheet = workBook.createSheet(sheetName);
} else {
sheet = workBook.createSheet(sheetName + "(" + n + ")");
}
sheet.getPrintSetup().setLandscape(true);
sheet.setColumnWidth(0, 1000);
sheet.setColumnWidth(1, 3000);
sheet.setColumnWidth(2, 3000);
sheet.setColumnWidth(3, 3000);
sheet.setColumnWidth(4, 3000);
sheet.setColumnWidth(5, 1700);
sheet.setColumnWidth(6, 800);
sheet.setColumnWidth(7, 2500);
sheet.setColumnWidth(8, 2000);
sheet.setColumnWidth(9, 3000);
sheet.setColumnWidth(10, 13000);
// 插入文件头
if (excelHead != null && excelHead.size() > 0) {
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < excelHead.size(); i++) {
// 在Label对象的子对象中指明单元格的位置和内容
XSSFCell cell = row.createCell(i);
cell.setCellValue(excelHead.get(i) + "");
}
}
// 插入数据
if (dataList != null && dataList.size() > 0) {
Integer dataLen = dataList.size() - EXCEL_MAX_ROW * n;
if (dataLen > EXCEL_MAX_ROW) {
dataLen = EXCEL_MAX_ROW;
}
for (int i = 0; i < dataLen; i++) {
Object lineData = dataList.get(i + EXCEL_MAX_ROW * n);
Row row = sheet.createRow(i + 1);
String thisAddress = "";
for (int j = 0; j < excelBody.size(); j++) {
Object valObj = getFieldValueByName(excelBody.get(j), lineData);
if (j >= startRow && j <= endRow) {
if(valObj instanceof Date){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
thisAddress += format.format(valObj);
}else{
thisAddress += valObj + "";
}
}
if (j < startRow) {
Cell cell = row.createCell(j);
if (j > 0) {
cell.setCellStyle(cellSt);
}
if (valObj != null) {
if(valObj instanceof Date){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
cell.setCellValue(format.format(valObj));
}else{
cell.setCellValue(valObj.toString());
}
} else {
cell.setCellValue("");
}
}
if (j > endRow) {
Cell cell = row.createCell(j - (endRow - startRow));
cell.setCellStyle(cellStyle);
if (valObj != null) {
if(valObj instanceof Date){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
cell.setCellValue(format.format(valObj));
}else{
cell.setCellValue(valObj + "");
}
} else {
cell.setCellValue("");
}
}
if (j == endRow) {
Cell cell = row.createCell(j - (endRow - startRow));
cell.setCellStyle(cellStyle);
cell.setCellValue(thisAddress);
}
}
}
}
}
workBook.write(out);
out.close();
} catch (IOException e) {
logger.error("导出数据异常", e);
throw new RuntimeException(e.getMessage());
}
}
/**
* 根据XSSFCell类型设置数据
*
* @param cell
* @return
*/
@Transactional(readOnly = false)
public static String getCellFormatValue(Cell cell) {
String cellvalue = "";
if (cell != null) {
// 判断当前Cell的Type
switch (cell.getCellType()) {
// 如果当前Cell的Type为NUMERIC
case XSSFCell.CELL_TYPE_NUMERIC:
cellvalue = String.valueOf(cell.getNumericCellValue());
break;
// 如果当前Cell的Type为STRIN
case XSSFCell.CELL_TYPE_STRING:
// 取得当前的Cell字符串
cellvalue = cell.getRichStringCellValue().getString();
break;
// 默认的Cell值
default:
cellvalue = "";
}
} else {
cellvalue = "";
}
if (cellvalue.endsWith(".0")) {
cellvalue = cellvalue.substring(0, cellvalue.length() - 2);
}
return cellvalue;
}
/**
* 读取Excel表格表头的内容
*
* @param
* @return String 表头内容的数组
*/
@Transactional(readOnly = false)
public static Map> readExcelTitle(XSSFWorkbook wb, InputStream is) {
Map> map = new HashMap>();
Sheet sheet = wb.getSheetAt(0);
Row row0 = sheet.getRow(0);
Row row1 = sheet.getRow(1);
// 标题总列数
int colNum = row0.getPhysicalNumberOfCells();
Map enTitleMap = new HashMap();
Map cnTitleMap = new HashMap();
for (int i = 0; i < colNum; i++) {
enTitleMap.put(i + "", getCellFormatValue(row0.getCell((short) i)));
cnTitleMap.put(i + "", getCellFormatValue(row1.getCell((short) i)));
}
map.put("enTitleMap", enTitleMap);
map.put("cnTitleMap", cnTitleMap);
return map;
}
public static Date formatDate(String d) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = formatter.parse(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
}
ParseUtils
package com.example.utils;
import com.alibaba.fastjson.JSON;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ParseUtils {
/**
* json转list
*
* @param
* @return list
*/
public static List> jsonToList2(String arr) {
List> returnList = new ArrayList>();
com.alibaba.fastjson.JSONArray mainArray = JSON.parseArray(arr);
for (int i = 0; i < mainArray.size(); i++) {
com.alibaba.fastjson.JSONArray paramObject = (com.alibaba.fastjson.JSONArray) mainArray.get(i);
Map map = new HashMap();
for (int j = 0; j < paramObject.size(); j++) {
map.put(""+j, paramObject.get(j));
}
returnList.add(map);
}
return returnList;
}
/**
* Object转Long
*
* @param Object
* @return Long
*/
public static Long objToLong(Object obj) {
if (obj != null && !"".equals(obj))
return Long.parseLong(obj.toString());
else
return null;
}
public static Integer objToInteger(Object obj) {
if (obj != null && !"".equals(obj))
return Integer.parseInt(obj.toString());
else
return null;
}
public static BigDecimal objToBigDecimal(Object obj) {
if (obj != null && !"".equals(obj))
return new BigDecimal(obj.toString());
else
return null;
}
/**
* Object转String
*
* @param Object
* @return String
*/
public static String objToString(Object obj) {
if (obj != null)
return obj.toString();
else
return null;
}
public static Date strToDate(String dateString){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(dateString);
return date;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static Date strToDateTime(String dateString){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(dateString);
return date;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static Boolean objToBoolean(Object obj){
return (Boolean)obj;
}
}
导入模板,示例:
/**
* 导入数据联系人,进行效验.
*
* @param files
* @return
* @throws IOException
*/
@SuppressWarnings("resource")
@ApiOperation(value = "POST导入数据联系人,进行效验按钮-website:customerMessage:edit", notes = "需要携带Token")
@RequiresPermissions("website:customerMessage:edit")
@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
@ResponseBody
public ResultBo> fileUpload(@RequestParam(value = "files") MultipartFile[] files) throws IOException {
//对文件大小进行判断是否是空文件
//对文件后缀进行判断
if (files.length == 0) {
return ResultBoFactory.createResultBo(ResultEnum.E1302_FILE_UPLOAD_FAIL);
}
//获取文件名字
String filename = files[0].getOriginalFilename();
//获取文件后缀
String filenames = StringUtils.substringAfterLast(filename, ".");
if (!Filelist.contains(filenames)) {
return ResultBoFactory.createResultBo(ResultEnum.E1303_FILE_UPLOAD_TYPE_FAIL);
}
//读取文件
InputStream inputStream = files[0].getInputStream();
//将用户id存入集合中
List customerInfoList = new ArrayList();
// 编写解析代码逻辑
// 基于.xls 格式解析 HSSF
// 1、 加载Excel文件对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
// 2、 读取一个sheet
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);//获取第一个sheet对象
//获取总行数
int rowNums = sheet.getLastRowNum();
if (rowNums > 200) {
return ResultBoFactory.createResultBo(ResultEnum.E1304_FILE_SIZE);
}
// 3、 读取sheet中每一行,一行数据 对应 一个区域对象
for (Row row : sheet) {
//设置一列的取值类型
row.getCell(0).setCellType(HSSFCell.CELL_TYPE_STRING);
// 第一行表头跳过
if (row.getRowNum() == 0) {
// 第一行 跳过
continue;
}
// 跳过id为空值的行,要求此行作废
if (row.getCell(0) == null
|| StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
return ResultBoFactory.createResultBo(ResultEnum.E1305_FILE_ERROR);
//continue;
}
//获取当前行
int rowNum = row.getRowNum() + 1;
String stringCellValue = row.getCell(0).getStringCellValue();
if (stringCellValue.indexOf(" ") != -1) {
return ResultBoFactory.createResultBo(ResultEnum.E4_OPERATION_FAIL.getCode(), "第" + rowNum + "行" + "存在非法字符!");
}
if (!stringCellValue.startsWith("C")) {
return ResultBoFactory.createResultBo(ResultEnum.E4_OPERATION_FAIL.getCode(), "第" + rowNum + "行" + "所输入用户编号格式不正确!");
}
CustomerInfo customerInfo = customerMessageService.queryCustomerInfoByCustomerSeq(stringCellValue);
if (customerInfo == null) {
return ResultBoFactory.createResultBo(ResultEnum.E4_OPERATION_FAIL.getCode(), "第" + rowNum + "行用户" + stringCellValue + "不存在!");
}
customerInfoList.add(stringCellValue);
}
int oldCustomerInfo = customerInfoList.size();//总数量
List customerList = removeDuplicate(customerInfoList);
int distinctNum = oldCustomerInfo - customerList.size();
Map hashMap = new HashMap<>();
hashMap.put("countExcleSuccess", customerList.size());//上传成功的数量
hashMap.put("distinctNum", distinctNum);//去重数量
//将联系人转成字符串
ObjectMapper mapper = new ObjectMapper();
String string = mapper.writeValueAsString(customerList);
hashMap.put("customerInfoId", string);
return ResultBoFactory.createResultBo(ResultEnum.E0_SUCCESS, hashMap);
}
//数据去重
private static List removeDuplicate(List list) {
LinkedHashSet set = new LinkedHashSet(list.size());
set.addAll(list);
list.clear();
list.addAll(set);
return list;
}