go 6年度参保匹配

记录参保匹配21-26年版本

go 复制代码
package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
	"github.com/xuri/excelize/v2"
)

var db *sql.DB
var tmpDir = "./tmp"

func initDB() {
	var err error
	db, err = sql.Open("sqlite3", "./bank.db?_journal=WAL&_sync=NORMAL")
	if err != nil {
		log.Fatal("打开bank.db失败:", err)
	}
	db.SetMaxOpenConns(1)
	db.SetMaxIdleConns(1)
	db.SetConnMaxLifetime(time.Hour)

}

func uploadExcel(c *gin.Context) {
	file, err := c.FormFile("excel")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "上传失败:" + err.Error()})
		return
	}
	savePath := filepath.Join(tmpDir, file.Filename)
	if err := c.SaveUploadedFile(file, savePath); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "保存文件失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 0, "path": savePath, "msg": "上传成功"})
}

func readIDList(path string) ([]string, error) {
	f, err := excelize.OpenFile(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	sheet := f.GetSheetList()[0]
	rows, err := f.GetRows(sheet)
	if err != nil {
		return nil, err
	}
	var ids []string
	for i, row := range rows {
		if i == 0 {
			continue
		}
		if len(row) > 0 {
			ids = append(ids, row[0])
		}
	}
	return ids, nil
}

func join(arr []string, sep string) string {
	res := ""
	for i, s := range arr {
		if i > 0 {
			res += sep
		}
		res += s
	}
	return res
}

func downloadFile(c *gin.Context) {
	fn := c.Query("fn")
	if fn == "" {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "文件名不能为空"})
		return
	}
	if _, err := os.Stat(fn); err != nil {
		c.JSON(http.StatusNotFound, gin.H{"msg": "文件不存在"})
		return
	}
	c.File(fn)
}
func indexPage(c *gin.Context) {
	html := `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>参保数据多条件匹配导出</title>
<style>
.box{width:600px;margin:40px auto;padding:20px;border:1px #ddd solid;border-radius:6}
p{color:#666}
button{padding:8px 20px;background:#0066cc;color:#fff;border:none;border-radius:4;cursor:pointer}
#download{background:#00994c;margin-top:15px;display:none}
select{padding:6px 10px;margin-bottom:10px;width:300px}
input{margin-bottom:10px}
</style>
</head>
<body>
<div class="box">
	<h3>参保数据批量匹配导出</h3>

	<p>第一步:选择参保年度</p>
	<select id="yearSel">
		<option value="cbone">2021</option>
		<option value="cbtwo">2022</option>
		<option value="cbthree">2023</option>
		<option value="cbfour">2024</option>
		<option value="cbfive">2025</option>
		<option value="cbsix" selected>2026</option>
	</select>

	<p>第二步:选择匹配字段</p>
	<select id="matchType">
		<option value="idcard">被保险人证件号</option>
		<option value="phone">电话</option>
		<option value="holder">投保人</option>
		<option value="insured">被保险人姓名</option>
	</select>

	<p>第三步:上传Excel,第一列存放对应匹配内容,第一行为表头</p>
	<input type="file" id="fileUp" accept=".xlsx">
	<br><br>
	<button id="matchBtn">执行匹配</button>
	<br>
	<a id="downLink" href="" download><button id="download">下载结果Excel</button></a>
	<div id="msg" style="margin-top:15px;color:#0066cc"></div>
</div>
<script>
let uploadPath = '';
const msgDom = document.getElementById('msg');
const downBtn = document.getElementById('download');
const downLink = document.getElementById('downLink');
const typeSel = document.getElementById('matchType');
const yearSel = document.getElementById('yearSel');

document.getElementById('fileUp').onchange = async function(){
	uploadPath = '';
	msgDom.innerText = '';
	downBtn.style.display = 'none';

	let fd = new FormData();
	fd.append('excel', this.files[0]);
	let res = await fetch('/api/upload', {method:'POST', body:fd});
	let data = await res.json();
	if(data.code === 0){
		uploadPath = data.path;
		msgDom.innerText = '文件上传完成,可执行匹配';
	}else{
		msgDom.innerText = data.msg;
	}
}

document.getElementById('matchBtn').onclick = async function(){
	if(!uploadPath){
		alert('请先上传Excel文件');
		return;
	}
	msgDom.innerText = '正在查询匹配中...';
	downBtn.style.display = 'none';

	try{
		let res = await fetch('/api/match-idcard', {
			method:'POST',
			headers:{'Content-Type':'application/json'},
			body:JSON.stringify({
				filePath: uploadPath,
				matchType: typeSel.value,
				tableName: yearSel.value
			})
		});
		let data = await res.json();
		msgDom.innerText = data.msg + ' 匹配条数:' + data.count;
		if(data.fileName){
			downLink.href = '/api/download?fn=' + data.fileName;
			downBtn.style.display = 'block';
			// 点击下载后自动刷新页面
			downLink.onclick = function(){
				setTimeout(()=>{
					location.reload();
				}, 800);
			}
		}
	}catch(err){
		msgDom.innerText = "请求异常:" + err;
	}
}
</script>
</body>
`
	c.Header("Content-Type", "text/html;charset=utf-8")
	c.String(http.StatusOK, html)
}

func matchIDCard(c *gin.Context) {
	type Req struct {
		FilePath  string `json:"filePath"`
		MatchType string `json:"matchType"`
		TableName string `json:"tableName"`
	}
	var req Req
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "参数错误"})
		return
	}

	// 校验合法表名,防止注入
	validTables := map[string]bool{
		"cbone":   true,
		"cbtwo":   true,
		"cbthree": true,
		"cbfour":  true,
		"cbfive":  true,
		"cbsix":   true,
	}
	if !validTables[req.TableName] {
		c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "非法年度数据表"})
		return
	}

	log.Printf("待读取Excel路径:%s,匹配类型:%s,查询表:%s", req.FilePath, req.MatchType, req.TableName)
	idList, err := readIDList(req.FilePath)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "读取Excel失败:" + err.Error()})
		return
	}

	log.Printf("Excel读取匹配值列表:%v", idList)
	log.Printf("匹配值总条数:%d", len(idList))

	if len(idList) == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 0, "count": 0, "msg": "Excel无匹配数据"})
		return
	}

	// 映射数据库字段
	var colName string
	switch req.MatchType {
	case "idcard":
		colName = "被保险人证件号"
	case "phone":
		colName = "电话"
	case "holder":
		colName = "付款人"
	case "insured":
		colName = "被保险人"
	default:
		c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "不支持的匹配类型"})
		return
	}

	f := excelize.NewFile()
	sheet := "匹配结果"
	f.SetSheetName("Sheet1", sheet)

	batchSize := 30000 // SQLite单批占位符安全上限 <999
	rowIdx := 1
	matchTotal := 0
	var cols []string

	for start := 0; start < len(idList); start += batchSize {
		end := start + batchSize
		if end > len(idList) {
			end = len(idList)
		}
		chunk := idList[start:end]
		placeholders := make([]string, len(chunk))
		args := make([]any, len(chunk))
		for i := range chunk {
			placeholders[i] = "?"
			args[i] = chunk[i]
		}

		sqlStr := fmt.Sprintf("SELECT * FROM `%s` WHERE `%s` IN (%s)", req.TableName, colName, join(placeholders, ","))
		log.Printf("执行SQL语句:%s", sqlStr)
		//log.Printf("SQL绑定参数:%v", args)

		rows, err := db.Query(sqlStr, args...)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "查询失败:" + err.Error()})
			return
		}
		// 第一批次写入表头
		if start == 0 {
			cols, err = rows.Columns()
			if err != nil {
				_ = rows.Close()
				c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "读取列失败"})
				return
			}
			log.Printf("数据库表字段:%v", cols)
			for idx, col := range cols {
				cell, _ := excelize.CoordinatesToCellName(idx+1, 1)
				f.SetCellValue(sheet, cell, col)
			}
		}

		vals := make([]any, len(cols))
		ptrs := make([]any, len(cols))
		for i := range vals {
			ptrs[i] = &vals[i]
		}
		for rows.Next() {
			rowIdx++
			if err := rows.Scan(ptrs...); err != nil {
				_ = rows.Close()
				c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "扫描行失败:" + err.Error()})
				return
			}
			matchTotal++
			for colIdx, val := range vals {
				cell, _ := excelize.CoordinatesToCellName(colIdx+1, rowIdx)
				f.SetCellValue(sheet, cell, val)
			}
		}
		closeErr := rows.Close()
		if closeErr != nil {
			log.Printf("关闭行失败:%v", closeErr)
		}

		if err := rows.Err(); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "行迭代失败:" + err.Error()})
			return
		}
	}
	log.Printf("数据库匹配到记录条数:%d", matchTotal)

	now := time.Now().Format("200601_150405")
	fn := fmt.Sprintf("%s_匹配_%s.xlsx", req.TableName, now)
	if err := f.SaveAs(fn); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "生成文件失败:" + err.Error()})
		return
	}
	log.Printf("导出文件名称:%s", fn)

	c.JSON(http.StatusOK, gin.H{
		"code":     0,
		"count":    matchTotal,
		"msg":      "匹配完成",
		"fileName": fn,
	})
}

func main() {
	gin.SetMode(gin.ReleaseMode)
	initDB()
	r := gin.Default()
	r.SetTrustedProxies(nil)
	r.GET("/", indexPage)
	api := r.Group("/api")
	{
		api.POST("/upload", uploadExcel)
		api.POST("/match-idcard", matchIDCard)
		api.GET("/download", downloadFile)
	}
	log.Println("服务启动 [http://127.0.0.1:8080](http://127.0.0.1:8080)")
	r.Run(":8080")
}
相关推荐
我不会起名字32227 分钟前
Go 内存与逃逸边界:栈分配、结构体对齐与零拷贝的 4 个取舍
性能优化·go·并发·逃逸分析·后端架构
BingoGo1 小时前
Laravel Go 高性能全栈框架发布
后端·go
MicrosoftReactor1 小时前
技术速递|Aspire 17 正式发布,已准备好投入生产使用
人工智能·ai·go·.net·agent·aspire
JaguarJack1 小时前
Laravel Go 高性能全栈框架发布
后端·go·laravel·服务端
疯华整猫1 天前
go vet 一行不报,单测全绿,服务却 leaking:AI 时代学 Go,重点是这三个它看不到的地方
后端·go·编程语言
goehou3 天前
Gin 中间件的 c.Next 和 c.Abort,我跑了四组验证
后端·中间件·go·gin
吴佳浩3 天前
我和 rust-anything:AI 时代,重写代码不再靠“信心“,而靠“证据“
人工智能·rust·go
Sailing7 天前
🔥🔥还在用 any 硬撑通用层?Go 泛型再不补,下一轮重构你就接不住了
后端·面试·go
Sailing8 天前
🔥🔥sql: waiting for connection 踩坑:不要一味调大 MaxOpenConns
后端·go·gin