vue中excel的導入和導出

1、導入

1.1 導入maven依賴

<dependency>
   <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.8</version>
</dependency>

1.2 sevice層、數據處理

public Boolean upLoadPowerData(MultipartFile multipartFile) {
        File file = null;
        InputStream inputStream = null;
        HSSFWorkbook workbook = null;
        HSSFSheet sheet = null;
        int sheetRowCount = 0;
        String sheetName = null;
        try {
            file = ExcelUtils.fileTransformation(multipartFile);
            if (file == null) {
                return false;
            }
            inputStream = new FileInputStream(file.getAbsolutePath());
            workbook = new HSSFWorkbook(inputStream);

            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
               // 對於sheet中的數據處理
                // 獲取當前sheet
                sheet = workbook.getSheetAt(i);
                // 獲取sheet總行數
                sheetRowCount = sheet.getPhysicalNumberOfRows();
                // 獲取sheet名稱
                sheetName = sheet.getSheetName();
                // 獲取當前sheet第一行、第一列數據
                sheet.getRow(0).getCell(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

1.3 service中使用到的工具類

public class ExcelUtils {
	//文件轉換MultipartFile ->File
    public static File fileTransformation(MultipartFile file) throws IOException {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
            return toFile;
        }
        return toFile;
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

1.4 controller層

@ApiOperation("上傳excel數據文件")
@PostMapping("/upload")
public R uploadExcel(@RequestParam MultipartFile file) throws IOException {
    return new R<>(demoService.upLoadPowerData(file));
}

1.5 前端頁面

使用了element-ui的上傳組件,詳細配置可以去看下element-ui的文檔

<el-upload
 class="upload-demo uploadData"
  style="text-align: right;margin-left: 10px"
  action="https://jsonplaceholder.typicode.com/posts/"
  accept=".xls,.xlsx"
  :before-upload="importExcel"
  :limit="1">
  <el-button slot="trigger" ref="file" size="small" class="addBtn"
             style="background-color: #f9a038;color:white;">數據導入
  </el-button>
</el-upload>

1.6 js請求

axios請求封裝

import request from '@/router/axios'
// 導入excel
export function uploadExcel(data) {
  return request({
    url: '/demo/upload',
    method: 'post',
    data: data
  })
}

js導入方法

importExcel(file) {
 this.loading = true;
  const data = new FormData();
  data.append('file', file);
  uploadExcel(data).then(res => {
    if (res.data.data) {
      this.$message({
        message: "導入成功!",
        type: "success"
      });
    } else {
      this.$message({
        message: "導入失敗,請校驗數據!",
        type: "warning"
      });
    }
    this.loading = false;
  })
}

2、導出

2.1 controller層

@ApiOperation("下載excel數據文件")
@GetMapping("/download/{demoId}")
public void downLoadExcel(@PathVariable Integer demoId, HttpServletResponse response) throws IOException {
	// 獲取workbook對象
   HSSFWorkbook workbook = demoService.downLoadPowerData(demoId, year);

   response.setCharacterEncoding("utf-8");
   response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("demo.xls", "UTF-8"));
   response.setContentType("application/vnd.ms-excel;charset=UTF-8");
   workbook.write(response.getOutputStream());
}

2.2 js請求

封裝axios請求

import request from '@/router/axios'
// 下載excel
export function downLoadExcel(demoId) {
  return request({
    url: '/demo/download/' + demoId ,
    method: 'get',
    responseType: 'blob'
  })
}

js方法處理

exportExcel() {
 this.loading = true;
  downLoadExcel(parseInt(this.demoId)).then(response => {
    const link = document.createElement('a');
    let blob = new Blob([response.data], {type: 'application/vnd.ms-excel;charset=UTF-8'});
    link.style.display = 'none';
    link.href = URL.createObjectURL(blob);
    link.download = "demo.xls";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    this.loading = false;
  });
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章