当前位置:   article > 正文

Django读取前端上传的CSV / Excel文件_django获取前端文件

django获取前端文件

前端上传文件代码:

<template>
	<div>
		<div>
			<el-upload class="upload-demo" ref="upload" action="http://127.0.0.1:8000/data/" :on-preview="handlePreview"
				:on-remove="handleRemove" :on-success="handleSuccess" :on-error='handleFail' :file-list="fileList"
				:multiple="false" :limit="1" :auto-upload="false">
				<el-button slot="trigger" size="small" type="primary">选择文件</el-button>
			</el-upload>
		</div>

		<div>
			<el-button slot="trigger" size="small" type="success" @click="submitUnpload()">上传文件</el-button>
		</div>
	</div>
</template>


<script>
	export default {
		data() {
			return {
				fileList: [],
				data: [],
			}
		},
		methods: {

			handleFail() {
				this.$message({
					type: 'error',
					message: '上传失败',
					duration: 1000
				})
			},
			// 成功上传到服务器后返回的内容
			handleSunccess(e) {
				this.data = e
			},

			// 上传文件到服务器
			submitUnpload() {
				this.$refs.upload.submit()
				this.$message({
					type: 'success',
					message: '上传成功',
					duration: 1000
				})
			},

			// 删除文件
			handleRemove(file) {
				this.$message({
					type: "success",
					message: "删除成功",
					duration: 1000
				})
			},
		}

	}
</script>

<style>
</style>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65

在这里插入图片描述

Django获取前端上传的文件:

class Data(APIView):
 	def post(self, request):
        file_obj = request.FILES.get("file")
        ......
  • 1
  • 2
  • 3
  • 4

通过csv模块读取csv文件,不需要打开文件,通过read()方法读取后传给csv.reader()

class Data(APIView):

 	def post(self, request):
 	
        file_obj = request.FILES.get("file")
		file_data = file_obj.read().decode("utf-8-sig")
        rows = csv.reader(io.StringIO(file_data), delimiter=',')
        
        for row in rows:
        	row #读取的数据
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

pandas读取:

class StatisticDmanday(APIView):

    def post(self, request):
    
        file_obj = request.FILES.get("file")
        df = pd.read_csv(file_obj)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

openpyxl读取excel文件:

class StatisticDmanday(APIView):

    def post(self, request):
    
 		wb = openpyxl.load_workbook(file_obj)
 		sheetnames = wb.get_sheet_names()
 		ws = wb.get_sheet_by_name(sheetnames[0])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号