导入excel
import org.springframework.web.multipart.MultipartFile; @ApiImplicitParams({ @ApiImplicitParam(name = "flag", value = "flag", dataType = "int", paramType = "query", example = "") }) @ResponseBody @PassLogin //for push @RequestMapping(value = "/importExcel", method = RequestMethod.POST) public Integer importExcel(@RequestParam MultipartFile file,Integer flag,HttpServletRequest request) throws IOException{ boolean FLAG;//身份状态 Workbook workbook = null; try { workbook = WorkbookFactory.create(file.getInputStream()); }catch (Exception e){ e.printStackTrace(); } Sheet sheet = workbook.getSheetAt(0); //示意访问sheet try { Site,Factory,ParameterType,ProcessOperCode,ProcessEqpType,MeasOperCode,MeasOperCode1,MeasEqpType,MeasEqpType1,ParameterName for(Row row : sheet) { row.getCell(0).setCellType(Cell.CELL_TYPE_STRING); if (StringUtils.isEmpty(row.getCell(0).getStringCellValue())) { break; } String site = (String) dealCell(row.getCell(0)); String factory = (String) dealCell(row.getCell(1)); String parameterType = (String) dealCell(row.getCell(2)); CharacterValueVo characterValueVo = new CharacterValueVo(); characterValueVo.setSite(site.toUpperCase()); characterValueVo.setFactory(factory.toUpperCase()); characterValueVo.setParameterType(parameterType); } } catch (Exception e) { e.printStackTrace(); throw new ReportException("导入失败,请检查excel格式是否符合规范!!"); } finally { workbook.close(); } return HttpStatus.SUCCESS; }
导出excel
@ApiImplicitParams({ @ApiImplicitParam(name = "flag", value = "flag", dataType = "int", paramType = "query", example = "") }) @ResponseBody @PassLogin //for push @RequestMapping(value = "/excel/exportBankCheckInfo", method = RequestMethod.POST) public void exportBankCheckInfo(HttpServletResponse response, HttpServletRequest request,@RequestBody CharacterValueVo characterValueVo, @RequestHeader(value = "site", required = false) String site) throws Exception { try { //.......................... LinkedList<CharacterValueVo> finalList = new LinkedList<>(); LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>(); //获取需要转出的excel表头的map字段 fieldMap.put("site","Site"); fieldMap.put("factory","factory"); fieldMap.put("parameterType","parametertype"); fieldMap.put("processOperCode","processOperCode"); ExcelUtils2.export(excelName,finalList,fieldMap,response); }catch (Exception e){ e.printStackTrace(); } }
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
public class ExcelUtils2 {
private static final Logger logger = LoggerFactory.getLogger(ExcelUtils2.class);
/**
* 导出模板
* @param filepath
* @param response
* @param <T>
*/
public static <T> void exportTemplate(String filepath, HttpServletResponse response) {
// 设置默认文件名为当前时间:年月日时分秒
String fileName = filepath.split("\\.")[0];
// 设置response头信息
response.reset();
try {
String excelName = new String(fileName.getBytes("UTF-8"),"UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.addHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(excelName,"UTF-8"));
//将文件输出
OutputStream output = response.getOutputStream();
FileInputStream fileInput = new FileInputStream(filepath);
int i = fileInput.available();
byte[] content = new byte[i];
fileInput.read(content);
output.write(content);
output.flush();
output.close();
} catch (Exception e) {
logger.info("导出Excel失败!");
logger.error(e.getMessage());
}
}
/**
* 导出Excel
*
* @param excelName 要导出的excel名称
* @param list 要导出的数据集合
* @param fieldMap 中英文字段对应Map,即要导出的excel表头
* @param response 使用response可以导出到浏览器
* @param <T>
*/
public static <T> void export(String excelName, List<T> list, LinkedHashMap<String, String> fieldMap, HttpServletResponse response) {
// 设置默认文件名为当前时间:年月日时分秒
if (excelName == null || excelName == "") {
excelName = new SimpleDateFormat("yyyyMMddhhmmss").format(
new Date()).toString();
}
// 设置response头信息
response.reset();
try {
String finalFileName = null;
if(excelName.endsWith(".xlsx")){
finalFileName = URLEncoder.encode(excelName,"UTF-8");
}else {
finalFileName = URLEncoder.encode(excelName,"UTF-8") +".xlsx";
}
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition","attachment;fileName=" + finalFileName);
} catch (Exception e1) {
logger.info(e1.getMessage());
}
try {
//创建一个WorkBook,对应一个Excel文件
XSSFWorkbook wb = new XSSFWorkbook();
//在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet)
XSSFSheet sheet = wb.createSheet(excelName);
//创建单元格,并设置值表头 设置表头居中
XSSFCellStyle style = wb.createCellStyle();
//创建一个居中格式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 填充工作表
fillSheet(sheet, list, fieldMap, style);
//将文件输出
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
logger.info("导出Excel失败!");
logger.error(e.getMessage());
}
}
/**
* 向工作表中填充数据
*
* @param sheet excel的工作表名称
* @param list 数据源
* @param fieldMap 中英文字段对应关系的Map
* @param style 表格中的格式
* @throws Exception 异常
*/
public static <T> void fillSheet(XSSFSheet sheet, List<T> list,
LinkedHashMap<String, String> fieldMap, XSSFCellStyle style) throws Exception {
// logger.info("向工作表中填充数据:fillSheet()");
// 定义存放英文字段名和中文字段名的数组
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
// 填充数组
int count = 0;
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
//在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
XSSFRow row = sheet.createRow((int) 0);
// 填充表头
for (int i = 0; i < cnFields.length; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
sheet.autoSizeColumn(i);
}
// 填充内容
for (int index = 0; index < list.size(); index++) {
row = sheet.createRow(index + 1);
// 获取单个对象
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
row.createCell(i).setCellValue(fieldValue);
}
}
}
/**
* 根据带路径或不带路径的属性名获取属性值,即接受简单属性名,
* 如userName等,又接受带路径的属性名,如student.department.name等
*
* @param fieldNameSequence 带路径的属性名或简单属性名
* @param o 对象
* @return 属性值
* @throws Exception 异常
*/
public static Object getFieldValueByNameSequence(String fieldNameSequence,
Object o) throws Exception {
// logger.info("根据带路径或不带路径的属性名获取属性值,即接受简单属性名:getFieldValueByNameSequence()");
Object value = null;
// 将fieldNameSequence进行拆分
String[] attributes = fieldNameSequence.split("\\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
// 根据数组中第一个连接属性名获取连接属性对象,如student.department.name
Object fieldObj = getFieldValueByName(attributes[0], o);
//截取除第一个属性名之后的路径
String subFieldNameSequence = fieldNameSequence
.substring(fieldNameSequence.indexOf(".") + 1);
//递归得到最终的属性对象的值
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
/**
* 根据字段名获取字段对象
*
* @param fieldName 字段名
* @param clazz 包含该字段的类
* @return 字段
*/
public static Field getFieldByName(String fieldName, Class<?> clazz) {
// logger.info("根据字段名获取字段对象:"+fieldName);
// 拿到本类的所有字段
Field[] selfFields = clazz.getDeclaredFields();
// 如果本类中存在该字段,则返回
for (Field field : selfFields) {
//如果本类中存在该字段,则返回
if (field.getName().equals(fieldName)) {
return field;
}
}
// 否则,查看父类中是否存在此字段,如果有则返回
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
//递归
return getFieldByName(fieldName, superClazz);
}
// 如果本类和父类都没有,则返回空
return null;
}
/**
* 根据字段名获取字段值
*
* @param fieldName 字段名
* @param o 对象
* @return 字段值
* @throws Exception 异常
*/
public static Object getFieldValueByName(String fieldName, Object o) throws Exception {
logger.info("根据字段名获取字段值:"+fieldName);
Object value = null;
//根据字段名得到字段对象
Field field = getFieldByName(fieldName, o.getClass());
//如果该字段存在,则取出该字段的值
if (field != null) {
field.setAccessible(true);//类中的成员变量为private,在类外边使用属性值,故必须进行此操作
value = field.get(o);//获取当前对象中当前Field的value
logger.info("根据字段名获取字段值:"+fieldName+" value="+value);
} else {
throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
return value;
}
/**
* 格式化单元格的内容
* @param cell
* @return
*/
private static Object getCellFormatValue(Cell cell){
Object cellValue = null;
if(cell != null){
//判断cell类型
switch(cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:{ cellValue = String.valueOf(cell.getNumericCellValue());break; }
case Cell.CELL_TYPE_FORMULA:{
//判断cell是否为日期格式
if(DateUtil.isCellDateFormatted(cell)){
//转换为日期格式YYYY-mm-dd
cellValue = cell.getDateCellValue();
}else{
//数字
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_STRING:{
cellValue = cell.getRichStringCellValue().getString();
break;
}
default:
cellValue = "";
}
}else{
cellValue = "";
}
return cellValue;
}
/**
* 将excel解析成list
* @param fileName
* @param is
* @param sheetIndex
* @return
* @throws Exception
*/
public static LinkedList<LinkedList<String>> convertExcelToList(String fileName,InputStream is,Integer sheetIndex) throws Exception{
//获取文件对象
Workbook wb = null;
LinkedList<LinkedList<String>> rowList = new LinkedList<>();
if(fileName.endsWith(".xls")){
wb = new HSSFWorkbook(is);
}else if(fileName.endsWith(".xlsx")){
wb = new XSSFWorkbook(is);
}
if(wb != null){
//获取第一个sheet
Sheet sheet = wb.getSheetAt(sheetIndex == null ? 0 : sheetIndex);
//获取最大行数
int rowNum = sheet.getPhysicalNumberOfRows();
//获取第一行
Row row = sheet.getRow(0);
//获取最大列数
int column = row.getPhysicalNumberOfCells();
for (int i = 1; i< rowNum; i++) {
LinkedList<String> cellList = new LinkedList<>();
row = sheet.getRow(i);
if(row !=null){
for (int j = 0; j < column; j++){
String cellData = (String) getCellFormatValue(row.getCell(j));
cellList.add(cellData);
}
}else{
break;
}
rowList.add(cellList);
}
}
return rowList;
}
}
注意:删除了部分代码(你懂的),但关键代码都保留下来了