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

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 queryString from 'query-string'
import { getToken } from '@/utils/auth'
import config from '@/config'
// 管理员列表
export function adminLists(params: any) {
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 })
}
// 导入
export const adminImportFile = '/system/admin/ImportFile'
// 导出
export function adminExportFile(params: any) {
// return request.get({ url: '/system/admin/ExportFile', params })
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({
components: {},
props: {
// 上传地址
url: {
type: String,
default: ''
},
// 上传文件类型
type: {
type: String,
@@ -79,7 +84,16 @@ export default defineComponent({
setup(props, { emit }) {
const userStore = useUserStore()
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(() => ({
token: userStore.token,
version: config.version

View File

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

View File

@@ -32,6 +32,17 @@
</template>
新增
</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">
<template #icon>
<icon name="el-icon-Download" />
@@ -98,7 +109,13 @@
</template>
<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 { useDictOptions } from '@/hooks/useDictOptions'
import { usePaging } from '@/hooks/usePaging'
@@ -135,6 +152,7 @@ const handleAdd = async () => {
await nextTick()
editRef.value?.open('add')
}
const exportFile = async () => {
await feedback.confirm('确定要导出?')
await adminExportFile(formData)

View File

@@ -1,6 +1,10 @@
package admin
import (
"bytes"
"fmt"
"io"
"net/http"
"strconv"
"x_admin/config"
"x_admin/core/request"
@@ -10,6 +14,7 @@ import (
"x_admin/util"
"github.com/gin-gonic/gin"
"github.com/xuri/excelize/v2"
)
// func AdminRoute(rg *gin.RouterGroup) {
@@ -67,6 +72,46 @@ func (ah AdminHandler) ExportFile(c *gin.Context) {
// 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 管理员列表
func (ah AdminHandler) List(c *gin.Context) {
var page request.PageReq

View File

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

View File

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

View File

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