excel表格导出 -- 下载功能
先装包
npm install file-saver
http请求配置 -- 对请求的url地址做筛选处理
http.interceptors.request.use(
function (config: any) {
const cookieTmToken = useCookie('tm-token')
config.headers.Authorization = cookieTmToken.value
config.responseType = 'json'
if (
config.url.includes('downloadTemplateFile') ||
config.url.includes('export') ||
config.url.includes('downLoad')
) {
config.responseType = 'blob'
}
return config
},
function (error) {
return Promise.reject(error)
}
)
使用
import { saveAs } from 'file-saver'
const historyOut = () => {
exportHistory({ ...historyId.value })
.then((response: any) => {
const blob = new Blob([response.data])
saveAs(blob,`历史数据.xlsx')
})
.catch(error => {
console.error('下载Excel文件时出错:', error)
})
}
excel表格导入 -- 上传按钮
组件封装
<el-button
v-if="prop.leadIn !== ''"
class="add"
type="primary"
:style="{ padding: '0px', height: '42px' }"
@click="spot"
>
<label
:form="
'uploadID' +
(((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
"
class=""
:style="{ padding: ' 20px', cursor: 'pointer' }"
>
<i class="ri-download-2-line mr-1"></i>
{{ prop.text }}
<input
:id="
'uploadID' +
(((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
"
ref="uploadInputFile"
accept=".xlsx"
class="hidden"
:style="{ display: 'none' }"
type="file"
@change="handleUpload"
/>
</label>
</el-button>
const emit: any = defineEmits(['spot'])
const prop: any = defineProps({
text: {
type: String,
default: '',
},
leadIn: {
type: String,
default: '',
},
callback: {
type: Function,
default: () => {},
},
})
const spot = () => {
emit('spot')
}
const uploadInputFile = ref()
const handleUpload = async (fileData: any) => {
try {
const file = fileData.target.files[0]
if (!file) {
return false
}
const txtName = '.xlsx'
const extName = file.name
.substring(file.name.lastIndexOf('.'))
.toLowerCase()
const extSize = file.size
if (!txtName.includes(extName)) {
ElMessage({
message: '请上传正确的文件格式!如:' + txtName,
type: 'warning',
})
uploadInputFile.value.value = null
return false
}
if (extSize / 1000 / 1000 > 50) {
ElMessage({
message: '请上传小于 50M 的文件!',
type: 'warning',
})
uploadInputFile.value.value = null
return false
}
if (!file) return false
ElMessage({
message: '导入中...',
type: 'success',
})
const formData: any = new FormData()
formData.append('file', file)
if (prop.params) {
Object.keys(prop.params).forEach(key => {
formData.append(key, prop.params[key])
})
}
let res: any = null
switch (prop.leadIn) {
case 'student':
res = await importStudent(formData)
break
case 'questionDimension':
res = await importQuestionDimension(formData)
break
case 'question':
res = await importQuestion(formData)
break
case 'scale':
res = await importScale(formData)
break
}
ElMessage({
message: '导入成功',
type: 'warning',
})
uploadInputFile.value.value = null
prop.callback(res)
} catch (error: any) {
uploadInputFile.value.value = null
}
}
组件使用
<BtnBox text="心理量表导入" leadIn="scale" :callback="scaleIn" />
const scaleIn = () => {
getData()
}