Java上传Excel表格转换为对象保存数据库

Posted java李杨勇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java上传Excel表格转换为对象保存数据库相关的知识,希望对你有一定的参考价值。

postman测试:

controller文件请求:在插入数据库之前可以做一些自己的业务逻辑处理

 @RequestMapping(value = "upload")
    @ResponseBody
    public synchronized R fileUpload(HttpServletRequest request)
    	try 
    		String[] fields =  "bbjs3510name", "lineName", "qjName", "bbjsgpsJd", "bbjsgpsWd", "remarks";
    		List<DlBbname> list = ExcelImportUtil.getImportData(fields, DlBbname.class, request);
    
    		dlBbnameService.insertOrUpdateBatch(list);
		 catch (Exception e) 
			logger.error("ERROR:", e);
		
    	return R.ok();
    

Excel导入工具类


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.util.WebUtils;

/**
 *Excel导入工具类
 */
public class ExcelImportUtil 
	
	/**
	 * 从上传文件中解析Excel
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws EncryptedDocumentException
	 * @throws InvalidFormatException
	 */
	public static Workbook getWorkbookFromRequest(HttpServletRequest request)
			throws IOException, EncryptedDocumentException, InvalidFormatException 
		InputStream is = null;
        MultipartHttpServletRequest multiRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
			Iterator<String> iterator = multiRequest.getFileNames();
			while (iterator.hasNext()) 
				MultipartFile multipartFile = multiRequest.getFile(iterator.next());
				if (multipartFile != null) 
					is = new ByteArrayInputStream(multipartFile.getBytes());
				
			
		Workbook wb = WorkbookFactory.create(is);
		return wb;
	

	/**
	 * 从上传文件中解析出数据对象
	 * @param sheetIndex 第几个sheet
	 * @param fields 解析字段
	 * @param clz 解析对象
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 */
	public static <T> List<T> getImportData(int sheetIndex, String[] fields, Class<T> clz, HttpServletRequest request)
			throws IOException, InvalidFormatException, InstantiationException, IllegalAccessException,
			NoSuchMethodException, InvocationTargetException, NoSuchFieldException, SecurityException 
		List<T> datas = new ArrayList<>();
		Workbook wb = getWorkbookFromRequest(request);
		Sheet sheet = wb.getSheetAt(sheetIndex);
		// 获取总行数
		int rows = sheet.getPhysicalNumberOfRows();
		if (rows >= 2) 
			for (int start = 1; start < rows; start++) 
				// 从第三行开始逐行获取
				Row row = sheet.getRow(start);
				if (row == null) 
					continue;
				

				if (fields != null) 
					T obj = clz.getDeclaredConstructor().newInstance();
					for (int i = 0; i < fields.length; i++) 
						Cell cell = row.getCell(i);
						String cellValue = getCellValue(cell);

						String fieldName = fields[i];
						Field field = null;
						try 
							field = obj.getClass().getDeclaredField(fieldName);
						 catch (NoSuchFieldException e) 
							field = obj.getClass().getSuperclass().getDeclaredField(fieldName);
						
						field.setAccessible(true);
						setFieldValue(field, obj, cellValue);
					
					datas.add(obj);
				
			
		
		return datas;
	
	
	/**
	 * 从上传文件中第一个sheet解析出数据对象
	 * @param fields
	 * @param clz
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 */
	public static <T> List<T> getImportData(String[] fields, Class<T> clz, HttpServletRequest request)
			throws IOException, InvalidFormatException, InstantiationException, IllegalAccessException,
			NoSuchMethodException, InvocationTargetException, NoSuchFieldException, SecurityException 
		return ExcelImportUtil.getImportData(0, fields, clz, request);
	

	private static String getCellValue(Cell cell) 
		String result = "";
		if (cell != null) 
			switch (cell.getCellType()) 
			// 数字类型 +日期类型
			case HSSFCell.CELL_TYPE_NUMERIC:
				if (HSSFDateUtil.isCellDateFormatted(cell)) // 处理日期格式、时间格式
					SimpleDateFormat sdf = null;
					if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) 
						sdf = new SimpleDateFormat("HH:mm");
					 else // 日期
						sdf = new SimpleDateFormat("yyyy-MM-dd");
					
					Date date = cell.getDateCellValue();
					result = sdf.format(date);
				 else if (cell.getCellStyle().getDataFormat() == 58) 
					// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					double value = cell.getNumericCellValue();
					Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
					result = sdf.format(date);
				 else 
					HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
					result = String.valueOf(dataFormatter.formatCellValue(cell));
				
				break;
			// String类型
			case HSSFCell.CELL_TYPE_STRING:
				result = String.valueOf(cell.getStringCellValue());
				break;
			case HSSFCell.CELL_TYPE_BLANK:
				result = "";
			default:
				result = null;
				break;
			
		

		return result;
	

	private static void setFieldValue(Field field, Object obj, String value) throws IllegalAccessException 
		Class<?> typeClass = field.getType();
		if (typeClass == int.class || typeClass == Integer.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, 0);
			 else 
				field.set(obj, Integer.valueOf(value));
			
		 else if (typeClass == short.class || typeClass == Short.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, 0);
			 else 
				field.set(obj, Short.valueOf(value));
			
		 else if (typeClass == byte.class || typeClass == Byte.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, 0);
			 else 
				field.set(obj, Byte.valueOf(value));
			
		 else if (typeClass == double.class || typeClass == Double.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, 0);
			 else 
				field.set(obj, Double.valueOf(value));
			
		 else if (typeClass == long.class || typeClass == Long.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, 0L);
			 else 
				field.set(obj, Long.valueOf(value));
			
		 else if (typeClass == String.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, "");
			 else 
				field.set(obj, value);
			
		 else if (typeClass == boolean.class || typeClass == Boolean.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, false);
			 else 
				field.set(obj, Boolean.valueOf(value));
			
		 else if (typeClass == BigDecimal.class) 
			if (StringUtils.isEmpty(value)) 
				field.set(obj, BigDecimal.ZERO);
			 else 
				field.set(obj, new BigDecimal(value));
			
		 else if (typeClass == Date.class) 
			field.set(obj, StringUtils.isEmpty(value) ? null : DateUtils.parseDate(value));
		 else 
			field.set(obj, value);
		
	

	/*public static void main(String[] args) 
		String[] fields =  "id" ;
		try 
			List<BaseMajor> userList = getImportData(fields, BaseMajor.class, null);
			for (BaseMajor u : userList) 
				System.out.println(u.getId());
			
		 catch (Exception e) 
			e.printStackTrace();
		
	*/


以上是关于Java上传Excel表格转换为对象保存数据库的主要内容,如果未能解决你的问题,请参考以下文章

将上传的Excel保存在数据库中

从excel表格读取数据用Java代码实现批量上传写入数据库

jsp 接收用户上传的excel,先对excle的数据进行筛选,再发到控制端该怎么做,求指导

如何把pdf文件转换为excel表格

如何将htm文档中的表格数据转换为Excel工作表

怎么讲csv格式转换为xlsx