MHTEvaluateResult2Excel.go 2.64 KB
Newer Older
Ford committed
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
package main

import (
	"fmt"
	"github.com/xuri/excelize/v2"
)

// 假设这是从数据库获取的学生信息和MHT测评结果的结构体
type StudentEvaluation struct {
	StudentId      string
	UserName       string
	Unit           string
	ClassNo        string
	EvaluateResult map[string]string
	Sex            string
}

// CreateEvaluationExcel 创建并填充学生信息和MHT测评结果的Excel表
func CreateEvaluationExcel(students []StudentEvaluation, filePath string) error {
	f := excelize.NewFile()
	// 创建一个新的工作表
	index, _ := f.NewSheet("MHT测评")
	// 设置工作表的标题行
	titles := []string{"学号", "学生姓名", "性别", "学校名称", "所在班级", "学习焦虑", "社交焦虑", "孤独倾向", "自责倾向", "过敏倾向", "生理症状", "恐怖倾向", "冲动倾向"}
	for i, title := range titles {
		// Excelize 使用A1表示法,列从A开始,行从1开始
		cell, _ := excelize.CoordinatesToCellName(i+1, 1)
		f.SetCellValue("MHT测评", cell, title)
	}

	// 填充学生信息和MHT测评结果
	for i, student := range students {
		values := []string{
			student.StudentId,
			student.UserName,
			student.Unit,
			student.ClassNo,
			student.EvaluateResult["LearningAnxiety"],
			student.EvaluateResult["AnxietyPeople"],
			student.EvaluateResult["LonelinessTendency"],
			student.EvaluateResult["SelfBlameTendency"],
			student.EvaluateResult["AllergicTendency"],
			student.EvaluateResult["PhysicalSign"],
			student.EvaluateResult["PhobicTendency"],
			student.EvaluateResult["ImpulsiveTendency"],
		}
		for j, value := range values {
			cell, _ := excelize.CoordinatesToCellName(j+1, i+2) // i+2 因为Excel表格的标题占据了第一行
			f.SetCellValue("MHT测评", cell, value)
		}
	}

	// 设置默认打开的工作表
	f.SetActiveSheet(index)
	// 保存文件到指定路径
	if err := f.SaveAs(filePath); err != nil {
		return err
	}
	return nil
}

func main() {
	// 假设这是从数据库查询到的数据
	students := []StudentEvaluation{
		{
			StudentId: "123456",
			UserName:  "张三",
			Sex:       "男",
			Unit:      "测试学校",
			ClassNo:   "3班",
			EvaluateResult: map[string]string{
				"LearningAnxiety":    "1",
				"AnxietyPeople":      "2",
				"LonelinessTendency": "3",
				"SelfBlameTendency":  "4",
				"AllergicTendency":   "5",
				"PhysicalSign":       "6",
				"PhobicTendency":     "7",
				"ImpulsiveTendency":  "8",
			},
		},
		// 可以添加更多学生数据
	}

	filePath := "MHTResults.xlsx"
	if err := CreateEvaluationExcel(students, filePath); err != nil {
		fmt.Println("创建Excel文件失败:", err)
		return
	}
	fmt.Println("Excel文件创建成功:", filePath)
}