前后端分离iview-admin二次开发+springboot导入excel的数据并插入到数据库

如题

参考

iview-admin导入excel组件
iview-excel导入数据库数据
springboot实现excel的上传并解析文件内容

注:此文并不涉及前后端文件上传,可参考大神的Spring Boot + Vue 前后端分离,两种文件上传方式总结,我也根据这篇做出来的

废话不说,直接上代码

一、准备工作介绍

我上传的excel是这样的:xlsx(xls也可以),第一行列名,一共五行数据,两列
前后端分离iview-admin二次开发+springboot导入excel的数据并插入到数据库_第1张图片

二、前端

<style lang="less">
  @import "./common.less";
</style>
<template>
  <div>
    <Card title="导入EXCEL">
      <Row>
        <Upload action="" :before-upload="handleBeforeUpload" accept=".xls, .xlsx">
          <Button icon="ios-cloud-upload-outline" :loading="uploadLoading" @click="handleUploadFile">读取文件</Button>
          
        </Upload>
        <Button @click="importData" type="info" style="margin-left:15px">上传</Button>
      </Row>
      <Row>
        <div class="ivu-upload-list-file" v-if="file !== null">
          <Icon type="ios-stats"></Icon>
            {
     {
      file.name }}
          <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove" @click.native="handleRemove()"></Icon>
        </div>
      </Row>
      <Row>
        <transition name="fade">
          <Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
            <div v-if="progressPercent == 100">
              <Icon type="ios-checkmark-circle"></Icon>
              <span>成功</span>
            </div>
          </Progress>
        </transition>
      </Row>
    </Card>
    <Row class="margin-top-10">
      <Table :columns="tableTitle" :data="tableData" :loading="tableLoading"></Table>
    </Row>
  </div>
</template>
<script>
import excel from '@/libs/excel'
export default {
     
  name: 'upload-excel',
  data () {
     
    return {
     
      uploadLoading: false,
      progressPercent: 0,
      showProgress: false,
      showRemoveFile: false,
      file: null,
      tableData: [],
      tableTitle: [],
      tableLoading: false
    }
  },
  methods: {
     
    importData() {
     
      const _this = this;
        if (this.file) {
     
          console.log(this.file)
          var formData = new FormData();
          formData.append("file", this.file);
          this.axios({
     
            method: "POST",
            url: `http://localhost:8080/import2`,
            data: formData,
            headers: {
     
              "Content-Type": "multipart/form-data"
            }
          }).then(function(resp) {
     
            _this.$Modal.success({
     
              title: "消息",
              content: "上传成功"
            });
          });
        } else {
     
          _this.$Modal.info({
     
            title: "消息",
            content: "请选择文件"
          });
        }
      // }
    },
    initUpload () {
     
      this.file = null
      this.showProgress = false
      this.loadingProgress = 0
      this.tableData = []
      this.tableTitle = []
    },
    handleUploadFile () {
     
      this.initUpload()
    },
    handleRemove () {
     
      this.initUpload()
      this.$Message.info('上传的文件已删除!')
    },
    handleBeforeUpload (file) {
     
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
     
        this.readFile(file)
        this.file = file
      } else {
     
        this.$Notice.warning({
     
          title: '文件类型错误',
          desc: '文件:' + file.name + '不是EXCEL文件,请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 读取文件
    readFile (file) {
     
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
     
        this.uploadLoading = true
        this.tableLoading = true
        this.showProgress = true
      }
      reader.onprogress = e => {
     
        this.progressPercent = Math.round(e.loaded / e.total * 100)
      }
      reader.onerror = e => {
     
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
     
        this.$Message.info('文件读取成功')
        const data = e.target.result
        const {
      header, results } = excel.read(data, 'array')
        const tableTitle = header.map(item => {
      return {
      title: item, key: item } })
        this.tableData = results
        this.tableTitle = tableTitle
        this.uploadLoading = false
        this.tableLoading = false
        this.showRemoveFile = true
      }
    }
  },
  created () {
     

  },
  mounted () {
     

  }
}
</script>

界面
前后端分离iview-admin二次开发+springboot导入excel的数据并插入到数据库_第2张图片

三、后端

1.导入POI依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
            <scope>compile</scope>
        </dependency>

2.controller

@Controller
public class filec {
     
    @Autowired
    private FormDao formDao;
    
    @RequestMapping(value="/import2")
    @ResponseBody
    public void importData2(MultipartFile file,HttpServletRequest req) throws IOException {
     
        InputStream inputStream = file.getInputStream();
        Workbook workbook = null;
        try {
     
            workbook = WorkbookFactory.create(inputStream);
            inputStream.close();
            //工作表对象
            Sheet sheet = workbook.getSheetAt(0);
            //总行数
            int rowLength = sheet.getLastRowNum() ;
            //工作表的列
            Row row = sheet.getRow(0);
            //总列数
            int colLength = row.getLastCellNum();
            System.out.println("总列数有多少列" + colLength);
            //得到指定的单元格
            Cell cell = row.getCell(0);
            for (int i = 1; i < rowLength +1; i++) {
     
                System.out.print("for");
                row = sheet.getRow(i);
                if (row != null)
                {
     
                    System.out.print("if");
                    Form form = new Form();
                    form.setValue1(row.getCell(0).getStringCellValue().trim());
                    form.setValue2(row.getCell(1).getStringCellValue().trim());
                    formDao.add(form);
                    System.out.print(form);
                }
             }
        } catch (Exception e) {
     
        }
    }
}

3.dao

@Mapper
public interface FormDao {
     
    @Insert("insert into testform(test,value1,value2)" +
            " values(#{test},#{value1},#{value2})")
    void add(Form form);

}

四、数据库

前后端分离iview-admin二次开发+springboot导入excel的数据并插入到数据库_第3张图片

你可能感兴趣的:(VUE,前后端,java,java,vue.js)