package main import ( "github.com/360EntSecGroup-Skylar/excelize" "github.com/golang/glog" "gopkg.in/yaml.v2" "io/ioutil" "path/filepath" ) func main() { glog.Info("开始-读取配置文件...") config := initFunc2() if config == nil { return } pathFile := config.Book savePath := config.Save sheetName := config.Sheet cellNum := config.CellNum long := config.Longs types := config.Types ranges := config.Ranges glog.Info("配置文件:", pathFile, savePath, sheetName, cellNum, long, types, ranges) xlsx, err := excelize.OpenFile(pathFile) if err != nil { glog.Error("打开文件失败!") return } dvRange := excelize.NewDataValidation(true) dvRange.Sqref = "A1:B2" dvRange.SetRange(10, 20, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorBetween) dvRange.SetError(excelize.DataValidationErrorStyleStop, "发现错误", "您输入的内容不符合规范") xlsx.AddDataValidation(sheetName, dvRange) err = xlsx.SaveAs(savePath) if err != nil { glog.Info("发生异常:", err) return } for _, s := range cellNum { glog.Info("xxx:", s) } //glog.Info("开始-为异常单元格设置指定样式...") //makeExcelStyle(xlsx, sheetName, cells) // //// Save xlsx file by the given path. //err = xlsx.SaveAs(pathFile) //if err != nil { // glog.Error("保存文件失败!") // return //} glog.Info("执行完成...") } /** readExcel 读取Excel,实现对比操作,完成统计异常单元格列表 */ func readExcel2(xlsx *excelize.File, sheetName string) (map[int]string, error) { cells, ii := map[int]string{}, 0 glog.Info(xlsx.GetCellValue(sheetName, "A1")) rows := xlsx.GetRows(sheetName) for _, row := range rows { for _, colCell := range row { if !(len(colCell) > 20) { cells[ii] = colCell ii++ } } } return cells, nil } /** makeExcelStyle 设置单元格样式 */ func makeExcelStyle2(xlsx *excelize.File, sheetName string, cells map[int]string) { xlsx.GetSheetIndex(sheetName) style, _ := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["#FF0000"],"pattern":1}}`) for _, s := range cells { xlsx.SetCellStyle(sheetName, s, s, style) } } /** initFunc 执行读取 yaml 配置文件 */ func initFunc2() *Config2 { path, _ := filepath.Abs("./") path += "\\config.yaml" glog.Info("读取配置文件:", path) path = "D:\\ViviCode\\golangs_learn\\golang_learn\\data_office\\get_excel_velidation\\config.yaml" load, err := load2(path) if err != nil { glog.Error("读取文件发生异常...") return nil } glog.Info("读取配置文件内容:", load) return load } type Config2 struct { Book string `yaml:"文件"` Save string `yaml:"另存为"` Sheet string `yaml:"页签"` RowNum int `yaml:"开始行"` CellNum []string `yaml:"开始列"` Longs []string `yaml:"长度"` Types []string `yaml:"类型"` Ranges []string `yaml:"范围"` } /** load 解析 Yaml 文件 */ func load2(path string) (*Config2, error) { conf := new(Config2) yamlFile, err := ioutil.ReadFile(path) if err != nil { glog.Info("发生异常:", err) return nil, err } err = yaml.Unmarshal(yamlFile, conf) if err != nil { glog.Error("Unmarshal:", err) return nil, err } return conf, err }