在 Java 中处理文件上传时,MultipartFile 是 Spring Framework 提供的用于处理 HTTP multipart/form-data 请求中上传文件的接口。以下是关于 MultipartFile 的详细介绍和使用示例:
MultipartFile 简介
MultipartFile 是 Spring 中表示上传文件的接口,它提供了一系列方法来获取文件信息、读取文件内容等。
主要用法
String getName() // 获取表单中文件参数的名称
String getOriginalFilename() // 获取原始文件名
String getContentType() // 获取文件内容类型
boolean isEmpty() // 判断文件是否为空
long getSize() // 获取文件大小(字节)
byte[] getBytes() // 获取文件内容的字节数组
InputStream getInputStream() // 获取文件输入流
void transferTo(File dest) // 将文件保存到目标位置
@RequestParam(required = true) MultipartFile file
使用文件类型:MultipartFile
处理excel工具类:
导入处理:
java
public class ExcelImport {
private static Logger log = LoggerFactory.getLogger(ExcelImport.class);
private Workbook wb;
private Sheet sheet;
private int headerNum;
private Map<String, Integer> titleMap;
private Set<String> requiredSet;
static final String REQUIRED_COLUMN_FLAG = "*";
private MappingType mappingType;
public ExcelImport(File file) throws InvalidFormatException, IOException {
this((File)file, 0, 0);
}
public ExcelImport(File file, int headerNum) throws InvalidFormatException, IOException {
this((File)file, headerNum, 0);
}
public ExcelImport(File file, int headerNum, Object sheetIndexOrName) throws InvalidFormatException, IOException {
this(file.getName(), new FileInputStream(file), headerNum, sheetIndexOrName, ExcelImport.MappingType.SEQUENCE);
}
public ExcelImport(MultipartFile multipartFile, int headerNum, Object sheetIndexOrName) throws InvalidFormatException, IOException {
this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndexOrName, ExcelImport.MappingType.SEQUENCE);
}
public ExcelImport(MultipartFile multipartFile, int headerNum, Object sheetIndexOrName, MappingType mappingType) throws InvalidFormatException, IOException {
this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndexOrName, mappingType);
}
public ExcelImport(String fileName, InputStream is, int headerNum, Object sheetIndexOrName, MappingType mappingType) throws InvalidFormatException, IOException {
this.mappingType = ExcelImport.MappingType.SEQUENCE;
try {
byte[] datas = IOUtils.toByteArray(is);
if (StringUtils.isBlank(fileName)) {
throw new HippoRuntimeException("导入文档为空!");
}
if (fileName.toLowerCase().endsWith("xls")) {
this.wb = new HSSFWorkbook(new ByteArrayInputStream(datas));
} else {
if (!fileName.toLowerCase().endsWith("xlsx")) {
throw new HippoRuntimeException("文档格式不正确!");
}
this.wb = new XSSFWorkbook(new ByteArrayInputStream(datas));
}
this.setSheet(sheetIndexOrName, headerNum);
if (mappingType.equals(ExcelImport.MappingType.NAME)) {
this.setTitleMap(headerNum);
}
} finally {
if (is != null) {
is.close();
}
}
}
private void addAnnotation(List<Object[]> annotationList, ExcelField ef, Object fOrM, ExcelField.Type type, String... groups) {
if (ef != null && (ef.type() == Type.ALL || ef.type() == type)) {
if (groups != null && groups.length > 0) {
boolean inGroup = false;
String[] var7 = groups;
int var8 = groups.length;
for(int var9 = 0; var9 < var8; ++var9) {
String g = var7[var9];
if (inGroup) {
break;
}
String[] var11 = ef.groups();
int var12 = var11.length;
for(int var13 = 0; var13 < var12; ++var13) {
String efg = var11[var13];
if (StringUtils.equals(g, efg)) {
inGroup = true;
annotationList.add(new Object[]{ef, fOrM});
break;
}
}
}
} else {
annotationList.add(new Object[]{ef, fOrM});
}
}
}
public Workbook getWorkbook() {
return this.wb;
}
public void setSheet(Object sheetIndexOrName, int headerNum) {
if (!(sheetIndexOrName instanceof Integer) && !(sheetIndexOrName instanceof Long)) {
this.sheet = this.wb.getSheet(EssObjectUtils.toString(sheetIndexOrName));
} else {
this.sheet = this.wb.getSheetAt(EssObjectUtils.toInteger(sheetIndexOrName));
}
if (this.sheet == null) {
throw new HippoRuntimeException("没有找到'" + sheetIndexOrName + "'工作表!");
} else {
this.headerNum = headerNum;
}
}
private void setTitleMap(int headerNum) {
this.mappingType = ExcelImport.MappingType.NAME;
this.titleMap = new HashMap();
this.requiredSet = new HashSet();
Row titleRow = this.getRow(headerNum - 1);
if (titleRow == null) {
throw new HippoRuntimeException("模版标题行(Excel第" + headerNum + "行)为空");
} else {
int totalCells = titleRow.getLastCellNum();
for(int j = titleRow.getFirstCellNum(); j < totalCells; ++j) {
String cellTitle = titleRow.getCell(j) == null ? "" : titleRow.getCell(j).toString();
if (cellTitle.length() >= 1) {
String convertTitle = cellTitle;
if (cellTitle.endsWith("*")) {
convertTitle = cellTitle.substring(0, cellTitle.length() - 1).trim();
}
if (cellTitle.endsWith("*") || cellTitle.startsWith("*")) {
this.requiredSet.add(convertTitle);
}
this.titleMap.put(convertTitle, j);
}
}
if (MapUtils.isEmpty(this.titleMap)) {
throw new HippoRuntimeException("模版标题行(Excel第" + headerNum + "行)为空");
}
}
}
public Row getRow(int rownum) {
Row row = this.sheet.getRow(rownum);
if (row == null) {
return null;
} else {
short cellNum = 0;
short emptyNum = 0;
Iterator<Cell> it = row.cellIterator();
while(it.hasNext()) {
++cellNum;
Cell cell = (Cell)it.next();
if (StringUtils.isBlank(cell.toString())) {
++emptyNum;
}
}
if (cellNum == emptyNum) {
return null;
} else {
return row;
}
}
}
public int getDataRowNum() {
return this.headerNum;
}
public int getLastDataRowNum() {
return this.sheet.getLastRowNum() + 1;
}
public int getLastCellNum() {
Row row = this.getRow(this.headerNum);
return row == null ? 0 : row.getLastCellNum();
}
public Object getCellValue(Row row, int column) {
if (row == null) {
return row;
} else {
Object val = "";
try {
Cell cell = row.getCell(column);
if (cell != null) {
if (cell.getCellType() == CellType.NUMERIC) {
Object val = cell.getNumericCellValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
val = DateUtil.getJavaDate((Double)val);
} else {
val = (new DecimalFormat("#.##")).format(val);
}
} else if (cell.getCellType() == CellType.STRING) {
val = cell.getStringCellValue();
} else if (cell.getCellType() == CellType.FORMULA) {
try {
val = cell.getStringCellValue();
} catch (Exception var8) {
FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
evaluator.evaluateFormulaCell(cell);
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case NUMERIC:
val = cellValue.getNumberValue();
break;
case STRING:
val = cellValue.getStringValue();
break;
case BOOLEAN:
val = cellValue.getBooleanValue();
break;
case ERROR:
val = ErrorEval.getText(cellValue.getErrorValue());
break;
default:
val = cell.getCellFormula();
}
}
} else if (cell.getCellType() == CellType.BOOLEAN) {
val = cell.getBooleanCellValue();
} else if (cell.getCellType() == CellType.ERROR) {
val = cell.getErrorCellValue();
}
}
return val;
} catch (Exception var9) {
return val;
}
}
}
public <E> List<E> getDataList(Class<E> cls, String... groups) throws InstantiationException, IllegalAccessException {
return this.getDataList(cls, true, groups);
}
public <E> List<E> getDataList(Class<E> cls, final boolean isThrowException, String... groups) throws InstantiationException, IllegalAccessException {
return this.getDataList(cls, new MethodCallback() {
public Object execute(Object... params) {
if (isThrowException) {
Exception ex = (Exception)params[0];
int rowNum = (Integer)params[1];
int columnNum = (Integer)params[2];
String val = (String)params[3];
throw new HippoRuntimeException("导入的Excel中[" + val + "]异常, 在第[" + rowNum + 1 + "]行,第[" + columnNum + 1 + "]列:" + ex.getMessage(), ex);
} else {
return null;
}
}
}, groups);
}
public <E> List<E> getDataList(Class<E> cls, MethodCallback exceptionCallback, String... groups) throws InstantiationException, IllegalAccessException {
List<Object[]> annotationList = new ArrayList();
Field[] fs = cls.getDeclaredFields();
Field[] var6 = fs;
int var7 = fs.length;
int var8;
int j;
for(var8 = 0; var8 < var7; ++var8) {
Field f = var6[var8];
ExcelFields efs = (ExcelFields)f.getAnnotation(ExcelFields.class);
if (efs != null && efs.value() != null) {
ExcelField[] var11 = efs.value();
int var12 = var11.length;
for(j = 0; j < var12; ++j) {
ExcelField ef = var11[j];
this.addAnnotation(annotationList, ef, f, Type.IMPORT, groups);
}
}
ExcelField ef = (ExcelField)f.getAnnotation(ExcelField.class);
this.addAnnotation(annotationList, ef, f, Type.IMPORT, groups);
}
Method[] ms = cls.getDeclaredMethods();
Method[] var23 = ms;
var8 = ms.length;
ExcelField ef;
int i;
for(i = 0; i < var8; ++i) {
Method m = var23[i];
ExcelFields efs = (ExcelFields)m.getAnnotation(ExcelFields.class);
if (efs != null && efs.value() != null) {
ExcelField[] var32 = efs.value();
j = var32.length;
for(int var35 = 0; var35 < j; ++var35) {
ef = var32[var35];
this.addAnnotation(annotationList, ef, m, Type.IMPORT, groups);
}
}
ExcelField ef = (ExcelField)m.getAnnotation(ExcelField.class);
this.addAnnotation(annotationList, ef, m, Type.IMPORT, groups);
}
if (this.mappingType.equals(ExcelImport.MappingType.NAME) && this.titleMap.size() != annotationList.size()) {
throw new HippoRuntimeException("Excel与标准模版不符,标题行个数[" + this.titleMap.size() + "]与标准模版标题行个数[" + annotationList.size() + "]不同");
} else {
Collections.sort(annotationList, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return (new Integer(((ExcelField)o1[0]).sort())).compareTo(new Integer(((ExcelField)o2[0]).sort()));
}
});
List<E> dataList = new ArrayList();
Set<Object> keySet = new HashSet();
for(i = this.getDataRowNum(); i < this.getLastDataRowNum(); ++i) {
E e = cls.newInstance();
Row row = this.getRow(i);
if (row != null) {
StringBuilder sb = new StringBuilder();
for(j = 0; j < annotationList.size(); ++j) {
Object[] os = (Object[])annotationList.get(j);
ef = (ExcelField)os[0];
int column = -1;
if (this.mappingType.equals(ExcelImport.MappingType.NAME)) {
if (this.titleMap.get(ef.name()) != null) {
column = (Integer)this.titleMap.get(ef.name());
}
} else if (this.mappingType.equals(ExcelImport.MappingType.COLUMN)) {
if (ef.column() != -1) {
column = ef.column();
}
} else {
column = j;
}
if (column == -1) {
throw new HippoRuntimeException("Excel与标准模版不匹配,[" + ef.name() + "]未填写");
}
Object val = this.getCellValue(row, column);
if (this.mappingType.equals(ExcelImport.MappingType.NAME) && this.requiredSet.contains(ef.name()) && (val == null || StringUtils.isBlank(val.toString()))) {
throw new HippoRuntimeException("导入的Excel"" + ef.name() + ""为必填项!");
}
if (val != null) {
if (ef.keyProp()) {
if (keySet.contains(val)) {
throw new HippoRuntimeException("导入数据有重复的" + ef.name() + ":" + val.toString());
}
keySet.add(val);
}
if (StringUtils.isNotBlank(ef.dictType())) {
}
Class<?> valType = Class.class;
if (os[1] instanceof Field) {
valType = ((Field)os[1]).getType();
} else if (os[1] instanceof Method) {
Method method = (Method)os[1];
if ("get".equals(method.getName().substring(0, 3))) {
valType = method.getReturnType();
} else if ("set".equals(method.getName().substring(0, 3))) {
valType = ((Method)os[1]).getParameterTypes()[0];
}
}
Object orgVal = val;
String mthodName;
try {
if (val != null) {
if (valType == String.class) {
mthodName = val.toString().trim();
if (StringUtils.endsWith(mthodName, ".0")) {
val = StringUtils.substringBefore(mthodName, ".0");
} else {
val = String.valueOf(val.toString()).trim();
}
} else if (valType == Integer.class) {
val = Double.valueOf(val.toString()).intValue();
} else if (valType == Long.class) {
val = Double.valueOf(val.toString()).longValue();
} else if (valType == Double.class) {
val = Double.valueOf(val.toString());
} else if (valType == Float.class) {
val = Float.valueOf(val.toString());
} else if (valType == Date.class) {
if (val instanceof String) {
if (StringUtils.isBlank((String)val)) {
val = null;
} else {
if (!checkDate((String)val)) {
throw new HippoRuntimeException("cell value [" + i + "," + column + "] 日期填写错误,请调整");
}
val = EssDateUtils.parseDate(val);
}
} else if (val instanceof Double) {
val = DateUtil.getJavaDate((Double)val);
}
} else if (valType == BigDecimal.class) {
val = new BigDecimal(String.valueOf(val));
} else if (ef.fieldType() != Class.class) {
val = ef.fieldType().getMethod("getValue", String.class).invoke((Object)null, val.toString());
} else {
val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), "fieldtype." + valType.getSimpleName() + "Type")).getMethod("getValue", String.class).invoke((Object)null, val.toString());
}
}
} catch (Exception var21) {
Exception ex = var21;
log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
val = null;
if (exceptionCallback != null) {
exceptionCallback.execute(new Object[]{ex, i, column, orgVal});
}
}
if (os[1] instanceof Field) {
ReflectUtils.invokeSetter(e, ((Field)os[1]).getName(), val);
} else if (os[1] instanceof Method) {
mthodName = ((Method)os[1]).getName();
if ("get".equals(mthodName.substring(0, 3))) {
mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
}
ReflectUtils.invokeMethod(e, mthodName, new Class[]{valType}, new Object[]{val});
}
}
sb.append(val + ", ");
}
dataList.add(e);
if (log.isDebugEnabled()) {
log.debug("Read success: [" + i + "] " + sb.toString());
}
}
}
return dataList;
}
}
static boolean checkDate(String str) {
try {
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd");
sd1.setLenient(false);
sd1.parse(str);
} catch (Exception var4) {
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
sd.parse(str);
} catch (Exception var3) {
return false;
}
}
return true;
}
public static enum MappingType {
SEQUENCE("S"),
COLUMN("C"),
NAME("N");
private final String value;
private MappingType(String value) {
this.value = value;
}
public String value() {
return this.value;
}
}
}
下载处理:
ExcelExportUtils
public class ExcelExportUtils {
public static final Logger logger = LoggerFactory.getLogger(ExcelExportUtils.class);
public ExcelExportUtils() {
}
public static void exportExcelFile(List<String> headers, List<List<String>> data, String fileName, HttpServletResponse response) {
XSSFWorkbook wb = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
wb = getWorkBook(headers, data, fileName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
ServletOutputStream out = response.getOutputStream();
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception var25) {
Exception var20 = var25;
logger.error("下载Excel文件异常", var20);
} finally {
IOException var18;
try {
if (bis != null) {
bis.close();
}
} catch (IOException var24) {
var18 = var24;
logger.error("下载Excel文件异常", var18);
}
try {
if (bos != null) {
bos.close();
}
} catch (IOException var23) {
var18 = var23;
logger.error("下载Excel文件异常", var18);
}
}
}
public static XSSFWorkbook getWorkBook(List<String> titleList, List<List<String>> contentlist, String sheetName) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFDataFormat format = workbook.createDataFormat();
XSSFSheet xssfSheet = workbook.createSheet(sheetName);
XSSFCellStyle headCellStyle = workbook.createCellStyle();
Font titleFont = workbook.createFont();
titleFont.setFontHeightInPoints((short)12);
titleFont.setBold(true);
headCellStyle.setFont(titleFont);
createHeader(xssfSheet, headCellStyle, titleList);
int size = contentlist.size();
XSSFCellStyle bodyCellStyle = workbook.createCellStyle();
bodyCellStyle.setDataFormat(format.getFormat("@"));
for(int i = 0; i < size; ++i) {
List<String> oneRow = (List)contentlist.get(i);
createContent(xssfSheet, bodyCellStyle, oneRow, i + 1);
}
return workbook;
}
private static void createHeader(XSSFSheet xssfSheet, XSSFCellStyle cellStyle, List<String> titleList) {
XSSFRow rowTitle = xssfSheet.createRow(0);
for(int i = 0; i < titleList.size(); ++i) {
xssfSheet.setColumnWidth(i, 5120);
Cell cellIndex = rowTitle.createCell(i);
cellIndex.setCellStyle(cellStyle);
cellIndex.setCellValue((String)titleList.get(i));
}
}
private static void createContent(XSSFSheet xssfSheet, XSSFCellStyle cellStyle, List<String> oneRow, int row) {
XSSFRow rowContent = xssfSheet.createRow(row);
for(int i = 0; i < oneRow.size(); ++i) {
Cell cellIndex = rowContent.createCell(i);
cellIndex.setCellStyle(cellStyle);
cellIndex.setCellValue((String)oneRow.get(i));
}
}
}
java
public class ExcelExportUtils {
public static final Logger logger = LoggerFactory.getLogger(ExcelExportUtils.class);
public ExcelExportUtils() {
}
public static void exportExcelFile(List<String> headers, List<List<String>> data, String fileName, HttpServletResponse response) {
XSSFWorkbook wb = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
wb = getWorkBook(headers, data, fileName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
ServletOutputStream out = response.getOutputStream();
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception var25) {
Exception var20 = var25;
logger.error("下载Excel文件异常", var20);
} finally {
IOException var18;
try {
if (bis != null) {
bis.close();
}
} catch (IOException var24) {
var18 = var24;
logger.error("下载Excel文件异常", var18);
}
try {
if (bos != null) {
bos.close();
}
} catch (IOException var23) {
var18 = var23;
logger.error("下载Excel文件异常", var18);
}
}
}
public static XSSFWorkbook getWorkBook(List<String> titleList, List<List<String>> contentlist, String sheetName) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFDataFormat format = workbook.createDataFormat();
XSSFSheet xssfSheet = workbook.createSheet(sheetName);
XSSFCellStyle headCellStyle = workbook.createCellStyle();
Font titleFont = workbook.createFont();
titleFont.setFontHeightInPoints((short)12);
titleFont.setBold(true);
headCellStyle.setFont(titleFont);
createHeader(xssfSheet, headCellStyle, titleList);
int size = contentlist.size();
XSSFCellStyle bodyCellStyle = workbook.createCellStyle();
bodyCellStyle.setDataFormat(format.getFormat("@"));
for(int i = 0; i < size; ++i) {
List<String> oneRow = (List)contentlist.get(i);
createContent(xssfSheet, bodyCellStyle, oneRow, i + 1);
}
return workbook;
}
private static void createHeader(XSSFSheet xssfSheet, XSSFCellStyle cellStyle, List<String> titleList) {
XSSFRow rowTitle = xssfSheet.createRow(0);
for(int i = 0; i < titleList.size(); ++i) {
xssfSheet.setColumnWidth(i, 5120);
Cell cellIndex = rowTitle.createCell(i);
cellIndex.setCellStyle(cellStyle);
cellIndex.setCellValue((String)titleList.get(i));
}
}
private static void createContent(XSSFSheet xssfSheet, XSSFCellStyle cellStyle, List<String> oneRow, int row) {
XSSFRow rowContent = xssfSheet.createRow(row);
for(int i = 0; i < oneRow.size(); ++i) {
Cell cellIndex = rowContent.createCell(i);
cellIndex.setCellStyle(cellStyle);
cellIndex.setCellValue((String)oneRow.get(i));
}
}
}
