修复导入获取数据下标不对

This commit is contained in:
xiangheng
2024-02-26 12:39:33 +08:00
parent df43e4e7dd
commit c27d7d4e1e
8 changed files with 129 additions and 25 deletions

View File

@@ -1,6 +1,7 @@
import request from '@/utils/request' import request from '@/utils/request'
import queryString from 'query-string' import queryString from 'query-string'
import { getToken } from '@/utils/auth' import { getToken } from '@/utils/auth'
import config from '@/config'
// 管理员列表 // 管理员列表
export function adminLists(params: any) { export function adminLists(params: any) {
return request.get({ url: '/system/admin/list', params }) return request.get({ url: '/system/admin/list', params })
@@ -36,9 +37,13 @@ export function adminListByDeptId(params: any) {
return request.get({ url: '/system/admin/ListByDeptId', params }) return request.get({ url: '/system/admin/ListByDeptId', params })
} }
// 导入
export const adminImportFile = '/system/admin/ImportFile'
// 导出 // 导出
export function adminExportFile(params: any) { export function adminExportFile(params: any) {
// return request.get({ url: '/system/admin/ExportFile', params }) // return request.get({ url: '/system/admin/ExportFile', params })
return (window.location.href = return (window.location.href =
`/api/admin/system/admin/ExportFile?token=${getToken()}&` + queryString.stringify(params)) `${config.baseUrl}${config.urlPrefix}/system/admin/ExportFile?token=${getToken()}&` +
queryString.stringify(params))
} }

View File

@@ -49,6 +49,11 @@ import { RequestCodeEnum } from '@/enums/requestEnums'
export default defineComponent({ export default defineComponent({
components: {}, components: {},
props: { props: {
// 上传地址
url: {
type: String,
default: ''
},
// 上传文件类型 // 上传文件类型
type: { type: {
type: String, type: String,
@@ -79,7 +84,16 @@ export default defineComponent({
setup(props, { emit }) { setup(props, { emit }) {
const userStore = useUserStore() const userStore = useUserStore()
const uploadRefs = shallowRef<InstanceType<typeof ElUpload>>() const uploadRefs = shallowRef<InstanceType<typeof ElUpload>>()
const action = ref(`${config.baseUrl}${config.urlPrefix}/common/upload/${props.type}`) let action = ''
if (props.url) {
if (props.url.startsWith('http')) {
action = props.url
} else {
action = `${config.baseUrl}${config.urlPrefix}${props.url}`
}
} else {
action = `${config.baseUrl}${config.urlPrefix}/common/upload/${props.type}`
}
const headers = computed(() => ({ const headers = computed(() => ({
token: userStore.token, token: userStore.token,
version: config.version version: config.version

View File

@@ -10,6 +10,7 @@
:style="{ width: setSize.imgWidth, height: setSize.imgHeight }" :style="{ width: setSize.imgWidth, height: setSize.imgHeight }"
> >
<img <img
v-show="backImgBase"
:src="'data:image/png;base64,' + backImgBase" :src="'data:image/png;base64,' + backImgBase"
alt="" alt=""
style="width: 100%; height: 100%; display: block" style="width: 100%; height: 100%; display: block"
@@ -74,6 +75,7 @@
}" }"
> >
<img <img
v-show="blockBackImgBase"
:src="'data:image/png;base64,' + blockBackImgBase" :src="'data:image/png;base64,' + blockBackImgBase"
alt="" alt=""
style=" style="

View File

@@ -32,6 +32,17 @@
</template> </template>
新增 新增
</el-button> </el-button>
<upload
class="mr-3"
:url="adminImportFile"
:data="{ cid: 0 }"
type="file"
:show-progress="true"
@change="resetPage"
>
<el-button type="primary">导入</el-button>
</upload>
<el-button type="primary" @click="exportFile"> <el-button type="primary" @click="exportFile">
<template #icon> <template #icon>
<icon name="el-icon-Download" /> <icon name="el-icon-Download" />
@@ -98,7 +109,13 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { adminLists, adminDelete, adminStatus, adminExportFile } from '@/api/perms/admin' import {
adminLists,
adminDelete,
adminStatus,
adminExportFile,
adminImportFile
} from '@/api/perms/admin'
import { roleAll } from '@/api/perms/role' import { roleAll } from '@/api/perms/role'
import { useDictOptions } from '@/hooks/useDictOptions' import { useDictOptions } from '@/hooks/useDictOptions'
import { usePaging } from '@/hooks/usePaging' import { usePaging } from '@/hooks/usePaging'
@@ -135,6 +152,7 @@ const handleAdd = async () => {
await nextTick() await nextTick()
editRef.value?.open('add') editRef.value?.open('add')
} }
const exportFile = async () => { const exportFile = async () => {
await feedback.confirm('确定要导出?') await feedback.confirm('确定要导出?')
await adminExportFile(formData) await adminExportFile(formData)

View File

@@ -1,6 +1,10 @@
package admin package admin
import ( import (
"bytes"
"fmt"
"io"
"net/http"
"strconv" "strconv"
"x_admin/config" "x_admin/config"
"x_admin/core/request" "x_admin/core/request"
@@ -10,6 +14,7 @@ import (
"x_admin/util" "x_admin/util"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/xuri/excelize/v2"
) )
// func AdminRoute(rg *gin.RouterGroup) { // func AdminRoute(rg *gin.RouterGroup) {
@@ -67,6 +72,46 @@ func (ah AdminHandler) ExportFile(c *gin.Context) {
// f.Write(c.Writer) // f.Write(c.Writer)
} }
// 导入文件
func (ah AdminHandler) ImportFile(c *gin.Context) {
// file, err := c.FormFile("file")
// if err != nil {
// c.String(500, "上传文件出错")
// }
// fmt.Println(file)
// 单文件
file, _, err := c.Request.FormFile("file")
if err != nil {
response.FailWithMsg(c, response.SystemError, "文件不存在")
return
}
defer file.Close()
// 创建缓冲区
buf := new(bytes.Buffer)
// 将文件内容复制到缓冲区
_, err = io.Copy(buf, file)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to read file")
return
}
// 创建Excel文件对象
f, err := excelize.OpenReader(bytes.NewReader(buf.Bytes()))
if err != nil {
c.String(http.StatusInternalServerError, "Failed to open Excel file")
return
}
importList := []SystemAuthAdminResp{}
err = excel.ImportExcel(f, &importList, 1, 2)
if err != nil {
fmt.Println(err)
}
for _, t := range importList {
fmt.Printf("%#v", t)
}
}
// list 管理员列表 // list 管理员列表
func (ah AdminHandler) List(c *gin.Context) { func (ah AdminHandler) List(c *gin.Context) {
var page request.PageReq var page request.PageReq

View File

@@ -32,6 +32,8 @@ func AdminRoute(rg *gin.RouterGroup) {
rg.GET("/admin/ExportFile", middleware.RecordLog("管理员导出"), handle.ExportFile) rg.GET("/admin/ExportFile", middleware.RecordLog("管理员导出"), handle.ExportFile)
rg.POST("/admin/ImportFile", handle.ImportFile)
} }
func RoleRoute(rg *gin.RouterGroup) { func RoleRoute(rg *gin.RouterGroup) {
// db := core.GetDB() // db := core.GetDB()

View File

@@ -29,6 +29,7 @@ func initRouter() *gin.Engine {
// 初始化gin // 初始化gin
gin.SetMode(config.Config.GinMode) gin.SetMode(config.Config.GinMode)
router := gin.New() router := gin.New()
router.MaxMultipartMemory = 8 << 20 // 8 MiB
// 设置静态路径 // 设置静态路径
router.Static(config.Config.PublicPrefix, config.Config.UploadDirectory) router.Static(config.Config.PublicPrefix, config.Config.UploadDirectory)

View File

@@ -30,28 +30,38 @@ func ImportBySheet(f *excelize.File, dst interface{}, sheetName string, headInde
return return
} }
// 获取在数组中得下标
func GetIndex(items []string, item string) int {
for i, v := range items {
if v == item {
return i
}
}
return -1
}
// 判断数组中是否包含指定元素 // 判断数组中是否包含指定元素
func IsContain(items interface{}, item interface{}) bool { // func IsContain(items interface{}, item interface{}) bool {
switch items.(type) { // switch items.(type) {
case []int: // case []int:
intArr := items.([]int) // intArr := items.([]int)
for _, value := range intArr { // for _, value := range intArr {
if value == item.(int) { // if value == item.(int) {
return true // return true
} // }
} // }
case []string: // case []string:
strArr := items.([]string) // strArr := items.([]string)
for _, value := range strArr { // for _, value := range strArr {
if value == item.(string) { // if value == item.(string) {
return true // return true
} // }
} // }
default: // default:
return false // return false
} // }
return false // return false
} // }
// 解析数据 // 解析数据
func importData(f *excelize.File, dst interface{}, sheetName string, headIndex, startRow int) (err error) { func importData(f *excelize.File, dst interface{}, sheetName string, headIndex, startRow int) (err error) {
@@ -98,11 +108,12 @@ func importData(f *excelize.File, dst interface{}, sheetName string, headIndex,
} }
cellValue = row[excelizeIndex] // 获取单元格的值 cellValue = row[excelizeIndex] // 获取单元格的值
} else { // 否则根据表头名称来拿数据 } else { // 否则根据表头名称来拿数据
if IsContain(heads, excelTag.Name) { // 当tag里的表头名称和excel表格里面的表头名称相匹配时 var index = GetIndex(heads, excelTag.Name)
if i >= len(row) { // 防止下标越界 if index != -1 {
if index >= len(row) { // 防止下标越界
continue continue
} }
cellValue = row[i] // 获取单元格的值 cellValue = row[index] // 获取单元格的值
} }
} }
// 根据字段类型设置值 // 根据字段类型设置值
@@ -110,6 +121,12 @@ func importData(f *excelize.File, dst interface{}, sheetName string, headIndex,
case reflect.Int: case reflect.Int:
v, _ := strconv.ParseInt(cellValue, 10, 64) v, _ := strconv.ParseInt(cellValue, 10, 64)
newData.Field(i).SetInt(v) newData.Field(i).SetInt(v)
case reflect.Uint:
v, _ := strconv.ParseUint(cellValue, 10, 64)
newData.Field(i).SetUint(v)
// case reflect.Uint8:
// v, _ := strconv.ParseUint(cellValue, 10, 64)
// newData.Field(i).SetUint(v)
case reflect.String: case reflect.String:
newData.Field(i).SetString(cellValue) newData.Field(i).SetString(cellValue)
} }