feat: 供应商导入数据、导出模板功能

This commit is contained in:
2025-07-30 10:46:05 +08:00
parent 2de0b7149b
commit 9c207b18e6
7 changed files with 273 additions and 5 deletions

View File

@@ -10,10 +10,13 @@ import org.nl.wms.basedata_manage.service.IMdCsSupplierbaseService;
import org.nl.wms.basedata_manage.service.dao.MdCsSupplierbase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;
@@ -61,4 +64,17 @@ public class SupplierController {
return new ResponseEntity<>(HttpStatus.OK);
}
@PostMapping("/importExcel")
@Log("导入单位")
public ResponseEntity<Object> importExcel(@RequestPart("file") MultipartFile file) {
iMdCsSupplierbaseService.importExcel(file);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("下载导入模板")
@GetMapping(value = "/downloadImportSuppTemplate", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadImportSuppTemplate(HttpServletResponse response) {
iMdCsSupplierbaseService.downloadImportSuppTemplate(response);
}
}

View File

@@ -4,7 +4,9 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import org.nl.common.domain.query.PageQuery;
import org.nl.wms.basedata_manage.service.dao.MdCsSupplierbase;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;
@@ -43,4 +45,10 @@ public interface IMdCsSupplierbaseService extends IService<MdCsSupplierbase> {
* @param ids 供应商标识集合
*/
void delete(Set<String> ids);
void importExcel(MultipartFile file);
void downloadImportSuppTemplate(HttpServletResponse response);
MdCsSupplierbase getByCode(String code);
}

View File

@@ -8,17 +8,27 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.nl.common.domain.query.PageQuery;
import org.nl.common.exception.BadRequestException;
import org.nl.common.utils.FileUtil;
import org.nl.common.utils.IdUtil;
import org.nl.common.utils.SecurityUtils;
import org.nl.wms.basedata_manage.enums.BaseDataEnum;
import org.nl.wms.basedata_manage.service.IMdCsSupplierbaseService;
import org.nl.wms.basedata_manage.service.dao.MdCsSupplierbase;
import org.nl.wms.basedata_manage.service.dao.MdPbMeasureunit;
import org.nl.wms.basedata_manage.service.dao.mapper.MdCsSupplierbaseMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -93,4 +103,67 @@ public class MdCsSupplierbaseServiceImpl extends ServiceImpl<MdCsSupplierbaseMap
public void delete(Set<String> ids) {
this.baseMapper.deleteBatchIds(ids);
}
@Override
public void importExcel(MultipartFile file) {
// 1. 校验文件
if (file.isEmpty()) {
throw new IllegalArgumentException("上传文件不能为空");
}
try (InputStream inputStream = file.getInputStream();
Workbook workbook = WorkbookFactory.create(inputStream)) {
DataFormatter formatter = new DataFormatter();
// 2. 获取第一个Sheet
Sheet sheet = workbook.getSheetAt(0);
// 3. 从第二行开始遍历 (索引1)
List<MdCsSupplierbase> dataList = new ArrayList<>();
for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
continue; // 跳过空行
}
Cell cell1 = row.getCell(0);
MdCsSupplierbase byCode = this.getByCode(formatter.formatCellValue(cell1));
if (ObjectUtil.isNotEmpty(byCode)) {
throw new BadRequestException("物料[" + cell1 + "]已存在!");
}
// 4. 读取6个字段
MdCsSupplierbase entity = new MdCsSupplierbase();
entity.setSupp_id(IdUtil.getStringId());
entity.setSupp_code(formatter.formatCellValue(cell1));
entity.setSupp_name(String.valueOf(row.getCell(1)));
entity.setIs_used("1");
entity.setCreate_id(SecurityUtils.getCurrentUserId());
entity.setCreate_name(SecurityUtils.getCurrentNickName());
entity.setCreate_time(DateUtil.now());
dataList.add(entity);
}
// 6. 批量保存
this.saveBatch(dataList);
} catch (IOException e) {
throw new RuntimeException("文件读取失败: " + e.getMessage());
} catch (Exception e) {
throw new RuntimeException("导入失败: " + e.getMessage());
}
}
@Override
public void downloadImportSuppTemplate(HttpServletResponse response) {
try {
byte[] byteByTemplate = FileUtil.getByteByTemplate("excel/supplier_template.xlsx");
FileUtil.download("供应商导入模板.xlsx", byteByTemplate, response);
} catch (Exception e) {
log.error(">>> 下载导入模板失败:", e);
}
}
@Override
public MdCsSupplierbase getByCode(String code) {
return getOne(new LambdaQueryWrapper<MdCsSupplierbase>().eq(MdCsSupplierbase::getSupp_code, code));
}
}

View File

@@ -125,7 +125,7 @@ public class MdPbMeasureunitServiceImpl extends ServiceImpl<MdPbMeasureunitMappe
try (InputStream inputStream = file.getInputStream();
Workbook workbook = WorkbookFactory.create(inputStream)) {
DataFormatter formatter = new DataFormatter();
// 2. 获取第一个Sheet
Sheet sheet = workbook.getSheetAt(0);
@@ -137,15 +137,15 @@ public class MdPbMeasureunitServiceImpl extends ServiceImpl<MdPbMeasureunitMappe
continue; // 跳过空行
}
Cell cell1 = row.getCell(0);
MdPbMeasureunit byCode = this.getByCode(String.valueOf(cell1), false);
MdPbMeasureunit byCode = this.getByCode(formatter.formatCellValue(cell1), false);
if (ObjectUtil.isNotEmpty(byCode)) {
throw new BadRequestException("物料[" + cell1 + "]已存在!");
throw new BadRequestException("物料[" + formatter.formatCellValue(cell1) + "]已存在!");
}
// 4. 读取6个字段
MdPbMeasureunit entity = new MdPbMeasureunit();
entity.setMeasure_unit_id(IdUtil.getStringId());
entity.setUnit_code(String.valueOf(cell1));
entity.setUnit_code(formatter.formatCellValue(cell1));
entity.setUnit_name(String.valueOf(row.getCell(1)));
entity.setQty_precision(new BigDecimal(String.valueOf(row.getCell(2))));
entity.setCreate_id(SecurityUtils.getCurrentUserId());

View File

@@ -0,0 +1,155 @@
<template>
<el-dialog
title="导入Excel文件"
append-to-body
:visible.sync="dialogVisible"
destroy-on-close
width="400px"
:show-close="true"
@close="close"
@open="open"
>
<el-upload
ref="upload"
class="upload-demo"
action=""
drag
:on-exceed="is_one"
:limit="1"
:auto-upload="false"
:multiple="false"
:show-file-list="true"
:on-change="uploadByJsqd"
:file-list="fileList"
accept=".xlsx,.xls"
>
<i class="el-icon-upload" />
<div class="el-upload__text">
将文件拖到此处
<em>点击上传</em>
</div>
<div slot="tip" class="el-upload__tip">
只能上传Excel文件且不超过10MB
<el-button type="text" @click="downloadImportTemplate">下载模板</el-button>
</div>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false"> </el-button>
<el-button type="primary" @click="submit"> </el-button>
</span>
</el-dialog>
</template>
<script>
import crudSupp from './supplierbase'
import CRUD, { crud } from '@crud/crud'
import { download2 } from '@/api/data'
import { downloadFile } from '@/utils'
export default {
name: 'UploadDialog',
mixins: [crud()],
components: {},
props: {
dialogShow: {
type: Boolean,
default: false
},
openParam: {
type: String
}
},
data() {
return {
dialogVisible: false,
fileList: [],
file1: ''
}
},
watch: {
dialogShow: {
handler(newValue, oldValue) {
this.dialogVisible = newValue
}
},
openParam: {
handler(newValue, oldValue) {
this.opendtlParam = newValue
}
}
},
methods: {
open() {
},
close() {
this.$emit('update:dialogShow', false)
},
is_one() {
this.crud.notify('只能上传一个excel文件', CRUD.NOTIFICATION_TYPE.WARNING)
},
// 文件校验方法
beforeAvatarUpload(file) {
// 不能导入大小超过2Mb的文件
if (file.size > 10 * 1024 * 1024) {
return false
}
return true
},
// 文件发生改变就会触发的事件
uploadByJsqd(file) {
this.file1 = file
},
downloadImportTemplate() {
crudSupp.downloadImportSuppTemplate().then(res => {
// 1. 创建Blob对象
const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
// 2. 创建临时下载链接
const downloadUrl = window.URL.createObjectURL(blob)
// 3. 创建隐藏的<a>标签
const link = document.createElement('a')
link.href = downloadUrl
// 设置下载文件名(根据后端返回或固定名称)
link.download = '供应商导入模板.xlsx'
// 4. 添加到DOM并触发点击
document.body.appendChild(link)
link.click()
// 5. 清理资源
document.body.removeChild(link)
window.URL.revokeObjectURL(downloadUrl)
}).catch(error => {
console.error('下载失败:', error)
// 这里可以添加错误提示如ElementUI的Message
this.$message.error('模板下载失败,请重试')
})
},
submit() {
if (this.beforeAvatarUpload(this.file1)) {
this.fileList.name = this.file1.name
this.fileList.url = ''
var formdata = new FormData()
formdata.append('file', this.file1.raw)
// excelImport请求接口 formdata传递参数
crudSupp.excelImport(formdata).then((res) => {
this.crud.notify('导入成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
this.$emit('tableChanged3', '')
this.$emit('update:dialogShow', false)
}).catch(err => {
const list = err.response.data.message
download2('/api/produceWorkorder/download', list).then(result => {
downloadFile(result, '错误信息汇总', 'xlsx')
crud.downloadLoading = false
})
})
} else {
this.crud.notify('文件过大请上传小于10MB的文件〜', CRUD.NOTIFICATION_TYPE.WARNING)
}
}
}
}
</script>

View File

@@ -24,4 +24,20 @@ export function edit(data) {
})
}
export default { add, edit, del }
export function excelImport(data) {
return request({
url: 'api/supplierbase/importExcel',
method: 'post',
data
})
}
export function downloadImportSuppTemplate(data) {
return request({
url: 'api/supplierbase/downloadImportSuppTemplate',
method: 'get',
responseType: 'blob'
})
}
export default { add, edit, del, downloadImportSuppTemplate, excelImport }