ajax上传文件与excel表格导入总结

一、excel导入:(还有别的插件像EasuPoi  ,ExcelUtil等)

1、需要导入包: Apache POI /

2、依赖: org.apache.poi poi 3.9

官方Demo:

$(element).upload({
                name: 'file',//上传组件的name属性,即
                action: '',//向服务器请求的路径
                enctype: 'multipart/form-data',//mime类型,默认即可
                params: {},//请求时额外传递的参数,默认为空
                autoSubmit: true,//是否自动提交,即当选择了文件,自动关闭了选择窗口后,是否自动提交请求。
                onSubmit: function() {},//提交表单之前触发事件
                onComplete: function() {},//提交表单完成后触发的事件
                onSelect: function() {}//当用户选择了一个文件后触发事件
        });

 

3、项目代码:


	

4、poi工具类:

package net.huadong.util;

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class POIUtil {
    private static Logger logger  = LoggerFactory.getLogger(POIUtil.class);
    private final static String xls = "xls";
    private final static String xlsx = "xlsx";

    /**
     * 读入excel文件,解析后返回
     * @param file
     * @throws IOException
     */
    public static List readExcel(MultipartFile file) throws IOException{
        //检查文件
        checkFile(file);
        //获得Workbook工作薄对象
        Workbook workbook = getWorkBook(file);

        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
        List list =null;
        if(workbook != null){
            //遍历Excel中所有的sheet
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if(sheet == null){
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum  = sheet.getFirstRowNum();

                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();

                //遍历除了第一行的所有行
                for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if(row == null){
                        continue;
                    }
                    //获得当前行的开始列
                    int firstCellNum = row.getFirstCellNum();
                    //获得当前行的列数
                    int lastCellNum = row.getPhysicalNumberOfCells();
                    System.out.println("当前列数:"+lastCellNum);
                    String[] cells = new String[row.getPhysicalNumberOfCells()];

                    //循环当前行
                    for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
                        Cell cell = row.getCell(cellNum);
                        cells[cellNum] = getCellValue(cell);
                    }
                 list = new ArrayList();
                    list.add(cells);


                }
            }
            // workbook.close();
        }

        return list;
    }
    public static void checkFile(MultipartFile file) throws IOException{
        //判断文件是否存在
        if(null == file){
            logger.error("文件不存在!");
            throw new FileNotFoundException("文件不存在!");
        }
        //获得文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否是excel文件
        if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
            logger.error(fileName + "不是excel文件");
            throw new IOException(fileName + "不是excel文件");
        }
    }
    public static Workbook getWorkBook(MultipartFile file) {
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象,表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if(fileName.endsWith(xls)){
                //2003
                workbook = new HSSFWorkbook(is);
            }else if(fileName.endsWith(xlsx)){
                //2007 及2007以上
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            logger.info(e.getMessage());
        }
        return workbook;
    }
    public static String getCellValue(Cell cell){
        String cellValue = "";
        if(cell == null){
            return cellValue;
        }
        //把数字当成String来读,避免出现1读成1.0的情况
        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }
}

 

5、后台代码:(inputFile一点跟name属性对应起来)Controller

 //excel上传
    @RequestMapping( method = RequestMethod.POST ,value="/uploadExcel")
    @ResponseBody
    public String uploadExcel(@RequestParam(value="inputFile") MultipartFile inputFile) throws IOException {
        String flag ="0";
            try{
                //这里得到的是一个集合,里面的每一个元素是String[]数组
                List list = POIUtil.readExcel(inputFile);
                codShipDataService.importExcelTable(list);

    } catch(Exception e){
                e.printStackTrace();
                flag = "1";
            }

        return flag;
    }

serviceImpl:

 @Override
    public void importExcelTable( List list) throws Exception {


        for(String[] strings:list ){
            CodShipData codShipData=  new CodShipData();
            codShipData.setShipOfficeNum(strings[0]);
            codShipData.setShortName(strings[1]);
            codShipData.setcShipNam(strings[2]);
            codShipData.seteShipNam(strings[3]);
            codShipData.setNationality(strings[4]);
            codShipData.setShipImo(strings[5]);
            codShipData.setShipMmsi(strings[6]);
            HdUtil.setCommonPro(true,codShipData);
            BigDecimal bd = new BigDecimal(strings[8]);
            codShipData.setShipGrossWgt(bd);
            this.insertSelective(codShipData);
        }

    }

参考这篇文章:https://blog.csdn.net/weixin_39816740/article/details/80508880

二、文件上传:


	

后台代码:

package net.huadong.controller;

import net.huadong.entity.CodAttachment;
import net.huadong.service.CodAttachmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Random;

@Controller
@RequestMapping(value = "/Upload")
public class UploadController {
    @Resource
    private CodAttachmentService codAttachmentService;
    Logger logger = LoggerFactory.getLogger(UploadController.class);
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/ToUpload")
    public Integer ToUploadFile(@RequestParam("inputFile") MultipartFile inputFile,HttpServletRequest request, HttpServletResponse response) {
        CodAttachment codAttachment = new CodAttachment();
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET,POST");
        response.addHeader("Content-Type","multipart/form-data");
        String originalFilename = null;
        String ct =null;
        String courseFile =null;
        try {

            if (inputFile.isEmpty()) {
                return 0;
            } else {
                originalFilename = inputFile.getOriginalFilename();
                // int i=originalFilename.lastIndexOf(".");
                // name = originalFilename.substring(0,i-1);
                long size = inputFile.getSize();
                ct = inputFile.getContentType();
                System.out.println("原始文件全路径名: " + originalFilename);
                System.out.println("文件大小:" + size + "KB");
                System.out.println("文件类型:" + ct);
                System.out.println("========================================");
            }
            // 1. 获取项目的全路径
            String root  = request.getSession().getServletContext().getRealPath("/webapp/files");
            String filename = inputFile.getOriginalFilename();
            System.out.println("filename文件:" + filename);
            //获取文件名,最后一个"\"后面的名字
            int index = filename.lastIndexOf("\\");
            if (index != -1) {
                filename = filename.substring(index + 1);
            }
            //生成唯一的文件名
            Random rnd = new Random();
            String savename = rnd.nextInt() + "_" + filename;
            System.out.println("savename文件:" + savename);
            //1. 根据文件名获取hashcode
            int hCode = filename.hashCode();
            // 将hashcode转化为无符号整数基数为16的整数参数的字符串
            String hex = Integer.toHexString(hCode);
            //2. 根据字符串生成文件目录
            File dirFile = new File(root, hex.charAt(0) + "/" + hex.charAt(1));
            dirFile.mkdirs();
            //4. 生成文件
            File destFile = new File(dirFile, savename);
            courseFile = destFile.getCanonicalPath();
            // 将文件保存到服务器相应的目录位置
            String tableId = request.getParameter("tableId");
            String enterpriseName = request.getParameter("enterpriseName");
            String type = request.getParameter("type");
            // System.out.println("fffgg=gggg"+saveEntity);
            inputFile.transferTo(destFile);
            codAttachment.setAttachmentName(originalFilename);
            codAttachment.setAttachmentType(type);
            codAttachment.setAttachmentUrl(courseFile);
            codAttachment.setTableId(tableId);
            codAttachment.setTableName(enterpriseName);
            codAttachmentService.saveUpload(codAttachment);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;

    }

}

注意下格式

你可能感兴趣的:(java)