<a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
@change="handleImportExcel">
<a-button type="primary" icon="import">导入数据</a-button>
</a-upload>
data() {
return {
url: {
importExcelUrl: 'cs/csBalanceAgent/importExcel'
}
}
},
methods: {
importExcelUrl: function() {
return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
},
/* 导入 */
handleImportExcel(info) {
console.log('info-----------------', info)
this.loading = true
if (info.file.status !== 'uploading') {
console.log('file==================', info.file, info.fileList)
}
if (info.file.status === 'done') {
this.loading = false
if (info.file.response.success) {
// this.$message.success(`${info.file.name} 文件上传成功`);
if (info.file.response.code === 201) {
let { message, result: { msg, fileUrl, fileName } } = info.file.response
let href = window._CONFIG['domianURL'] + fileUrl
this.$warning({
title: message,
content: (<div>
<span>{msg}</span><br />
<span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
</div>
)
})
} else {
this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
}
// this.loadData()
this.$refs.tablePage.refreshTable()
} else {
this.$message.error(`${info.file.name} ${info.file.response.message}.`)
}
} else if (info.file.status === 'error') {
this.loading = false
if (info.file.response.status === 500) {
let data = info.file.response
const token = Vue.ls.get(ACCESS_TOKEN)
if (token && data.message.includes('Token失效')) {
this.$error({
title: '登录已过期',
content: '很抱歉,登录已过期,请重新登录',
okText: '重新登录',
mask: false,
onOk: () => {
store.dispatch('Logout').then(() => {
Vue.ls.remove(ACCESS_TOKEN)
window.location.reload()
})
}
})
}
} else {
this.$message.error(`文件上传失败: ${info.file.msg} `)
}
}
},
}
/**
* 通过excel导入数据
*
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
return csBalanceAgentService.importExcelData(file);
}
@Override
public Result<?> importExcelData(MultipartFile file) {
List<CsBalanceAgent> list = null;
ImportParams importParams = new ImportParams();
importParams.setTitleRows(1);
importParams.setHeadRows(2);
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), CsBalanceAgent.class, importParams);
} catch (Exception e) {
e.printStackTrace();
}
if (list == null) {
return Result.error("没有有效的数据,导入数据失败");
}
this.saveBatch(list);
return Result.OK("导入成功");
}
以下代码可以替换上面的importExcelData方法
@Override
public Result<?> importExcelData(MultipartFile file) {
List<CsCustomNeed> list = null;
// 设置Excel导入参数
ImportParams importParams = new ImportParams();
importParams.setTitleRows(1); // 标题行数,即Excel中的第一行是标题行
importParams.setHeadRows(2); // 表头行数,即Excel中的第二行是表头行
try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
list = new ArrayList<>(); // 创建一个空的列表来存储解析后的数据
int rowCount = sheet.getLastRowNum(); // 获取行数,excel中的行数从0开始
for (int rowIndex = importParams.getHeadRows(); rowIndex <= rowCount; rowIndex++) {
Row row = sheet.getRow(rowIndex); // 获取当前行
if (row != null) {
CsCustomNeed obj = new CsCustomNeed(); // 创建CsCustomNeed对象
// 设置对象属性值,根据实际需求进行修改
obj.setConsignee(getCellValue(row.getCell(0))); // 设置第一列的值
obj.setProductPackage(getCellValue(row.getCell(1))); // 设置第二列的值
obj.setNeedNum(getCellValue(row.getCell(2))); // 设置第三列的值
obj.setQualityRequire(getCellValue(row.getCell(3))); // 设置第四列的值
obj.setFormula(getCellValue(row.getCell(4))); // 设置第五列的值
obj.setPackageRequire(getCellValue(row.getCell(5))); // 设置第六列的值
obj.setDeliveryTime(getCellValue(row.getCell(6))); // 设置第七列的值
obj.setRemark(getCellValue(row.getCell(7))); // 设置第八列的值
list.add(obj); // 将当前行的对象添加到列表中
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (list == null || list.isEmpty()) {
return Result.error("没有有效的数据,导入数据失败");
}
this.saveBatch(list); // 批量保存数据
return Result.OK("导入成功");
}
// 辅助方法,获取单元格的值,包括公式结果处理
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
// 获取单元格类型
CellType cellType = cell.getCellType();
if (cellType == CellType.FORMULA) {
// 如果单元格类型为公式,需要通过公式求值器获取计算结果
FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
CellValue cellValue = evaluator.evaluate(cell);
cellType = cellValue.getCellType();
// 根据单元格类型返回相应的值
if (cellType == CellType.NUMERIC) {
return String.valueOf(cellValue.getNumberValue());
} else if (cellType == CellType.STRING) {
return cellValue.getStringValue();
} else if (cellType == CellType.BOOLEAN) {
return String.valueOf(cellValue.getBooleanValue());
} else if (cellType == CellType.ERROR) {
return ErrorEval.getText(cellValue.getErrorValue());
} else {
return null;
}
} else if (cellType == CellType.NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else if (cellType == CellType.STRING) {
return cell.getStringCellValue();
} else if (cellType == CellType.BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else {
return null;
}
}
/**
* 详细解释getCellValue()方法的功能。
*
* @param cell 单元格对象
* @return 单元格的值
*/
// 解释开始
// 此方法用于获取单元格的值,包括公式结果的处理。
// 首先判断单元格是否为空,如果为空则返回null。
// 获取单元格类型,根据不同的类型进行相应的处理。
// 当单元格类型为公式时,需要使用公式求值器来获取计算结果。
// 接下来根据计算结果的类型,返回相应的值。
// 若为数值类型,则返回数值的字符串表示。
// 若为字符串类型,则直接返回字符串值。
// 若为布尔类型,则返回布尔值的字符串表示。
// 若为错误类型,则根据错误值获取对应的错误字符串
这段代码用于从Excel文件中导入数据,并将数据保存到数据库中。以下是对代码的详细解释:
- 首先,设置了Excel导入的参数,如标题行数和表头行数。
- 使用
WorkbookFactory.create(file.getInputStream())
方法打开Excel文件,并创建一个Workbook对象。- 获取第一个工作表(Sheet)。
- 创建一个空的列表来存储解析后的数据。
- 获取工作表的行数,并遍历每一行。
- 获取当前行(Row)对象。
- 对于不为空的行,创建一个CsCustomNeed对象。
- 设置CsCustomNeed对象的属性值,根据Excel中的列顺序来设置对应的属性值。
- 将CsCustomNeed对象添加到列表中。
- 如果列表为空,则返回导入失败的结果。
- 调用
saveBatch(list)
方法,使用批量操作将数据保存到数据库中。- 返回导入成功的结果。
请注意,代码中的
getCellValue()
方法用于获取Excel单元格的值,并根据需要进行解析和转换。此方法可能需要根据您的具体需求进行修改。另外,错误处理部分只是简单的打印了异常堆栈信息,您可以根据实际情况进行适当修改。