导入Excel数据存入数据库

整体思路:

导入Excel表格,将表格中的数据读取出并导入数据库。

注意:表格中的列的数值获取时要与对象的属性相对应。

1.上传文件时,先根据文件的 后缀,判断excel版本创建对应的Workbook

2.获取IO流中的数据,组装成List<List<Object>>

    2.1表格中的数值类型读取时要先进行判断,转成字符串。

 3.解析List<List<Object>>将List<Object>取出存入对象

步骤一:配置pom依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Excel_operation</groupId>
  <artifactId>Excel_operation</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
   <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
  </parent>
  
  <dependencies>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web </artifactId>
		</dependency>

	 <!-- spring-webmvc    我们 要进行控制类的处理 -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-webmvc</artifactId>
		    <!-- <version>4.3.14.RELEAdSE</version>  parent中 spring boot包含了spring的版本号--> 
		</dependency>
		
		<!-- 文件导入导出 -->
	    <dependency>
	       <groupId>org.apache.poi</groupId>
	       <artifactId>poi</artifactId>
	       <version>3.9</version>
	    </dependency>
	    
	    <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
		
  </dependencies>
       
    <build>   <!-- 插件,可通过插件进行运行 (可不进行配置)-->
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
  
  
  
  
</project>

步骤二:建立一个启动类

package com.excel.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExcelMain {
	
     public static void main(String[] args) {
		SpringApplication.run(ExcelMain.class, args);
	}
}

步骤三:建立一个实体对象

package com.excel.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExcelMain {
	
     public static void main(String[] args) {
		SpringApplication.run(ExcelMain.class, args);
	}
}

步骤四:编写上传接口

package com.excel.test.im;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.excel.test.entity.Student;
import com.excel.test.util.ExcelUtil;

@RestController
@RequestMapping(value = "/excel")
public class ImportFile {
     
	@Autowired
	 private ExcelUtil excelUtil;
	
	 @RequestMapping(value = "/import")
	  public String importExcel(HttpServletRequest request) {
		 //将request转换成一个上传文件的MultipartHttpServletRequest
		  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		  MultipartFile file = multipartRequest.getFile("upfile");
		  InputStream in = null;
		  List<List<Object>> listObject = null;
		  try {
		  if(file.isEmpty()) {
			 throw new Exception( "文件不存在");
		  }
		   in = file.getInputStream();
		   listObject = excelUtil.getListByExcel(in, file.getOriginalFilename());
		   in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		  //创建一个List存入对应的对象值
		  List<Student> stuList = new ArrayList<Student>();
		  for(int i = 0;i < listObject.size(); i++) {
			  //取出List<List<Object>>中的List<Object>
			  List<Object> lo = listObject.get(i);
			  Student student = new Student();
			  student.setName(String.valueOf(lo.get(0)));  //这里要对应
			  student.setCode(String.valueOf(lo.get(1)));
			  student.setDate(excelUtil.parseDate(String.valueOf(lo.get(2))));
			  stuList.add(student);
			  //接下来便可进行数据库插入
		  }
		  return "插入数据成功";
	  }
	
}

其中

根据文件的后缀,自适应上传文件的版本,

获取IO流中的数据,组装成List<List<Object>>,

将字符串转换成日期,

对表格中的数据进行格式化, 

自定义处理日期 的处理都在工具类中进行。

package com.excel.test.util;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;

@Controller
public class ExcelUtil {
	
     private final static String excel2003L = ".xls";      //2003- 版本的excel  
     private final static String excel2007L = ".xlsx";     //2007+ 版本的excel 
     
     
     /**
      * 根据文件的后缀,自适应上传文件的版本
      * @param in
      * @param fileName
      * @return
      * @throws Exception
      */
     public Workbook getWorkbook(InputStream in,String fileName) throws Exception {
    	 Workbook book = null;
    	 String fileType = fileName.substring(fileName.lastIndexOf("."));
    	 if(excel2003L.equals(fileType)) {
    		 book = new HSSFWorkbook(in);
    	 }else if(excel2007L.equals(fileType)) {
    		 book = new XSSFWorkbook(in);
    	 }else {
    		 throw new Exception("解析文件格式有误!");
    	 }
		return book;
     }
     
     /**
      * 自定义处理日期
      * @author Ejiao
      *
      */
    public static class XSSFDateUtil extends DateUtil{
    	protected static int absoluteDay(Calendar cal,boolean use1904windowing) {
    		return DateUtil.absoluteDay(cal, use1904windowing);
    	}
    }
     
     
     /**
      * 对表格中的数据进行格式化
      * @param cell
      * @return
      */
     @SuppressWarnings("unused")
	public Object getCellValue(Cell cell) {
    	 String strCell = "";
    	 switch(cell.getCellType()) {
    	   case XSSFCell.CELL_TYPE_STRING:  //字符串
    		   strCell = cell.getStringCellValue();
    		   break;
    	   case XSSFCell.CELL_TYPE_BOOLEAN:  //判断
    		   strCell = String.valueOf(cell.getBooleanCellValue());
    		   break;
    	   case XSSFCell.CELL_TYPE_BLANK:  //空白
    		   strCell = "";
    		   break;
    	   case XSSFCell.CELL_TYPE_FORMULA: //公式
    		   strCell = String.valueOf(cell.getNumericCellValue());
    		   DecimalFormat df = new DecimalFormat("#.########");
    		   strCell = df.format(Double.valueOf(strCell));
    		  break;
    	   case XSSFCell.CELL_TYPE_NUMERIC:
    		   if(XSSFDateUtil.isCellDateFormatted(cell)) {  //如果是date类型
    			   strCell = new SimpleDateFormat("yyyy-MM-dd").format(XSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
    		   }else {
    			   strCell = String.valueOf(cell.getNumericCellValue());
    			   DecimalFormat df1 = new DecimalFormat("#.#########");
                   strCell=df1.format(Double.valueOf(strCell));
    		   }
    		   break;
    	   default:
    		   strCell = "";
    		   break;
    	 }
    	 if(strCell.equals("") || strCell == null) {
    		 return "";
    	 }
    	 if(cell == null) {
    		 return "";
    	 }
    	 return strCell;
     }
     
     /**
      * 将字符串转换成日期
      * @param str
      * @return
      */
     public Date parseDate(String str) {
    	 DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
    	 try {
			return date.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	 return null;
     }
     
     
     
     /**
      * 获取IO流中的数据,组装成List<List<Object>>
      * @param in
      * @param fileName
      * @return
     * @throws Exception 
      */
     public List<List<Object>> getListByExcel(InputStream in,String fileName) throws Exception{
    	 List<List<Object>> list = new ArrayList<List<Object>>();
    	 Sheet sheet = null;
    	 Row row = null;
    	 Cell cell =null;
    	 //创建Excel工作簿
    	 Workbook book = this.getWorkbook(in, fileName);
    	 if(book == null) {
    		 throw new Exception("创建Exception为空");
    	 }
    	 //遍历Excel中所有的sheet
    	 for(int i = 0;i < book.getNumberOfSheets(); i++) {
    		  sheet = book.getSheetAt(i);
    		  if(sheet != null) {
    			  for(int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++ ) {
    				  row = sheet.getRow(j);
    				  if(row == null || row.getFirstCellNum() == j) {
    					  continue;
    				  }
    				  //遍历所有的列
    				  List<Object> li = new ArrayList<Object>();
    				  for(int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
    					  cell = row.getCell(y);
    					  li.add(this.getCellValue(cell));
    				  }
    				  list.add(li);
    			  }
    		  }
    	 }
    	 return list;
     }
     
}

猜你喜欢

转载自blog.csdn.net/sinat_35821285/article/details/81240452