Java上传excel,读取excel,xlsx和xls两种类型。读入数据库

这个小工具是去年在公司做东西的时候学会的,不是本人 自己写的

这是工具类

package com.ruowei.Utils;

import com.ruowei.exception.BusinessException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author 隋全通(copy环球)
 * @Date 2019/4/17 14:36
 * @Description读excel 文件的方法接口,读取直接存放数据库
 * @Param
 * @return
 **/
public class ObjectExcelRead {

    /**
     * @param filepath //文件路径
     * @param filename //文件名
     * @param startrow //开始行号
     * @param startcol //开始列号
     * @param sheetnum //sheet
     * @return list
     */
    public static List<Object> readExcel(String filepath, String filename, int startrow, int startcol, int sheetnum) {
        List<Object> varList = new ArrayList<Object>();

        try {
            File target = new File(filepath);
            FileInputStream fi = new FileInputStream(target);
            //进行版本选择解析方式
            Workbook wb = null;
            if (filename.endsWith(".xlsx")) {
                //
                wb = new XSSFWorkbook(fi);

            } else if (filename.endsWith(".xls")) {
                wb = new HSSFWorkbook(fi);
            } else {
                throw new BusinessException("不是Excel文件!",-2);
            }

            Sheet sheet = wb.getSheetAt(sheetnum);                    //sheet 从0开始
            int rowNum = sheet.getLastRowNum() + 1;                    //取得最后一行的行号

            for (int i = startrow; i < rowNum; i++) {                    //行循环开始

                PageData varpd = new PageData();

                Row row = sheet.getRow(i);                            //行
                int cellNum = row.getLastCellNum();                    //每行的最后一个单元格位置

                for (int j = startcol; j < cellNum; j++) {                //列循环开始

                    Cell cell = row.getCell(Short.parseShort(j + ""));
                    String cellValue = null;
                    if (null != cell) {
                        switch (cell.getCellType()) {                    // 判断excel单元格内容的格式,并对其进行转换,以便插入数据库
                            case 0:
                                DecimalFormat format = new DecimalFormat("#");
                                //cellValue = String.valueOf((int) cell.getNumericCellValue()); //int 类型操作
                                cellValue = format.format(cell.getNumericCellValue());
                                break;
                            case 1:
                                cellValue = cell.getStringCellValue();
                                break;
                            case 2:
                                cellValue = cell.getNumericCellValue() + "";
                                // cellValue = String.valueOf(cell.getDateCellValue());
                                break;
                            case 3:
                                cellValue = "";
                                break;
                            case 4:
                                cellValue = String.valueOf(cell.getBooleanCellValue());
                                break;
                            case 5:
                                cellValue = String.valueOf(cell.getErrorCellValue());
                                break;
                        }
                    } else {
                        cellValue = "";
                    }

                    varpd.put("var" + j, cellValue);

                }
                varList.add(varpd);
            }

        } catch (Exception e) {
            System.out.println(e);
        }

        return varList;
    }
}

接口controller

package com.ruowei.boot.controller;

import com.ruowei.Utils.*;
import com.ruowei.boot.model.Student;
import com.ruowei.boot.service.StudentService;
import org.apache.ibatis.session.SqlSession;
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 java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author 隋全通
 * @Date 2019/4/17 14:36
 * @Description读excel 文件的方法接口,读取直接存放数据库
 * @Param
 * @return
 **/
@RestController
@RequestMapping("/api")
public class ReadRxcelContrroller extends BaseApi {

    @Autowired
    private StudentService service;


    @RequestMapping("/ReadRxcelContrroller")
    public Success ReadRxcelContrroller(MultipartFile file) throws IOException {
        Success success = new Success(false);
        try {
            //读取默认
            InputStream resourceAsStream = ReadRxcelContrroller.class.getResourceAsStream("/param.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            //创建时间名称的文件
            String dateString = new SimpleDateFormat("yyyyMMddHHmmss").format((new Date()));
            //存放路径后半段
            String relativePath = "file/" + dateString;
            //路径
            String fileLoad = properties.getProperty("param.db") + relativePath + "/";
            //如果文件不存在直接自动创建
            File file1 = new File(fileLoad);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            //文件名称
            String originalFilename = file.getOriginalFilename();
            //为了兼容ie  在ie 中会出现路径问题 详细看打印出来的路径
            String fileName = originalFilename.substring(originalFilename.lastIndexOf("\\") + 1);
//        System.out.println(fileName);
            //文件的完整路径
            String filePath = fileLoad + fileName;
            //文件上传功能
            file.transferTo(new File(filePath));
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath,
                    fileName, 1, 0, 0); // 执行读EXCEL操作,读出的数据导入List//
            // 2:从第3行开始;0:从第A列开始;0:第0个shee
            /**
             * var0 :姓名 var1 :志愿者编号 var2 :岗位 var3 :积分 var4 :服务时长 var5 :报名时间
             *
             */
            List<Student> list = new ArrayList<>();
            for (int i = 0; i < listPd.size(); i++) {

                PageData pageData = listPd.get(i);
                String name = (String) pageData.get("var0");
                String number = (String) pageData.get("var1");
                String work = (String) pageData.get("var2");
                Integer NTEGRAL = Integer.valueOf(pageData.get("var3").toString());
                float helptime = Float.valueOf(pageData.get("var4").toString());
                String starttime = (String) pageData.get("var5");
                Student student = new Student();
                if (!CheckUtil.isEmpty(starttime)) {
                    Date date = org.apache.poi.ss.usermodel.DateUtil
                            .getJavaDate(Double.valueOf(starttime));
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println(format.format(date));
                    student.setStartDate(format);
                }
                student.setName(name);
                student.setNumber(number);
                student.setWork(work);
                student.setHelptime(helptime);
                student.setNTEGRAL(NTEGRAL);
                list.add(student);
            }
            return success;

        } catch (Exception e) {
            throw e;
        }


    }

    @Override
    public Object excuteApi(SqlSession session, Map<String, Object> paramMap) {
        return null;
    }

}

里面的一些数据库的service和dao层以及mapper.xml就不给大家上传

你可能感兴趣的:(javaweb)