From 8a335225c705232fe1174755a1b1ea475456b864 Mon Sep 17 00:00:00 2001 From: xuri Date: Thu, 24 Mar 2022 00:19:30 +0800 Subject: [PATCH] Format code, update documentation and remove exported variable `XMLHeaderByte` --- calc.go | 366 +++++++++++++++++++++++---------------------- calc_test.go | 2 +- cell.go | 55 ++++--- cell_test.go | 2 +- chart.go | 2 +- chart_test.go | 2 +- col.go | 21 ++- comment.go | 2 +- crypt.go | 6 +- crypt_test.go | 2 +- datavalidation.go | 21 +-- drawing.go | 2 +- errors.go | 4 +- excelize.go | 9 +- excelize_test.go | 14 +- lib.go | 26 ++-- merge_test.go | 2 +- numfmt.go | 10 +- picture.go | 4 +- pivotTable.go | 10 +- pivotTable_test.go | 6 +- rows.go | 2 +- sheet.go | 42 +++--- sheet_test.go | 2 +- sheetview.go | 4 +- sparkline.go | 2 +- stream.go | 2 +- stream_test.go | 2 +- styles.go | 6 +- styles_test.go | 4 +- table.go | 8 +- templates.go | 6 - xmlCalcChain.go | 4 +- xmlContentTypes.go | 2 +- xmlStyles.go | 2 +- xmlTable.go | 2 +- 36 files changed, 330 insertions(+), 328 deletions(-) diff --git a/calc.go b/calc.go index e2dec32..f707ee5 100644 --- a/calc.go +++ b/calc.go @@ -282,11 +282,11 @@ func (fa formulaArg) ToBool() formulaArg { func (fa formulaArg) ToList() []formulaArg { switch fa.Type { case ArgMatrix: - list := []formulaArg{} + var args []formulaArg for _, row := range fa.Matrix { - list = append(list, row...) + args = append(args, row...) } - return list + return args case ArgList: return fa.List case ArgNumber, ArgString, ArgError, ArgUnknown: @@ -1452,7 +1452,7 @@ func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (arg formulaArg, e if cellRanges.Len() > 0 { arg.Type = ArgMatrix for row := valueRange[0]; row <= valueRange[1]; row++ { - matrixRow := []formulaArg{} + var matrixRow []formulaArg for col := valueRange[2]; col <= valueRange[3]; col++ { var cell, value string if cell, err = CoordinatesToCellName(col, row); err != nil { @@ -1629,10 +1629,11 @@ func (fn *formulaFuncs) bassel(argsList *list.List, modfied bool) formulaArg { n4++ n2 *= n4 t = result + r := x1 / n1 / n2 if modfied || add { - result += (x1 / n1 / n2) + result += r } else { - result -= (x1 / n1 / n2) + result -= r } max-- add = !add @@ -1979,9 +1980,9 @@ func (fn *formulaFuncs) COMPLEX(argsList *list.List) formulaArg { if argsList.Len() > 3 { return newErrorFormulaArg(formulaErrorVALUE, "COMPLEX allows at most 3 arguments") } - real, i, suffix := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Front().Next().Value.(formulaArg).ToNumber(), "i" - if real.Type != ArgNumber { - return real + realNum, i, suffix := argsList.Front().Value.(formulaArg).ToNumber(), argsList.Front().Next().Value.(formulaArg).ToNumber(), "i" + if realNum.Type != ArgNumber { + return realNum } if i.Type != ArgNumber { return i @@ -1991,7 +1992,7 @@ func (fn *formulaFuncs) COMPLEX(argsList *list.List) formulaArg { return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE) } } - return newStringFormulaArg(cmplx2str(complex(real.Number, i.Number), suffix)) + return newStringFormulaArg(cmplx2str(complex(realNum.Number, i.Number), suffix)) } // cmplx2str replace complex number string characters. @@ -2226,7 +2227,7 @@ func (fn *formulaFuncs) ERFC(argsList *list.List) formulaArg { return fn.erfc("ERFC", argsList) } -// ERFC.PRECISE function calculates the Complementary Error Function, +// ERFCdotPRECISE function calculates the Complementary Error Function, // integrated between a supplied lower limit and infinity. The syntax of the // function is: // @@ -3773,7 +3774,7 @@ func (fn *formulaFuncs) GCD(argsList *list.List) formulaArg { } var ( val float64 - nums = []float64{} + nums []float64 ) for arg := argsList.Front(); arg != nil; arg = arg.Next() { token := arg.Value.(formulaArg) @@ -3890,7 +3891,7 @@ func (fn *formulaFuncs) LCM(argsList *list.List) formulaArg { } var ( val float64 - nums = []float64{} + nums []float64 err error ) for arg := argsList.Front(); arg != nil; arg = arg.Next() { @@ -3995,12 +3996,12 @@ func (fn *formulaFuncs) LOG10(argsList *list.List) formulaArg { // minor function implement a minor of a matrix A is the determinant of some // smaller square matrix. func minor(sqMtx [][]float64, idx int) [][]float64 { - ret := [][]float64{} + var ret [][]float64 for i := range sqMtx { if i == 0 { continue } - row := []float64{} + var row []float64 for j := range sqMtx { if j == idx { continue @@ -4037,7 +4038,7 @@ func det(sqMtx [][]float64) float64 { func (fn *formulaFuncs) MDETERM(argsList *list.List) (result formulaArg) { var ( num float64 - numMtx = [][]float64{} + numMtx [][]float64 err error strMtx [][]formulaArg ) @@ -4050,7 +4051,7 @@ func (fn *formulaFuncs) MDETERM(argsList *list.List) (result formulaArg) { if len(row) != rows { return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE) } - numRow := []float64{} + var numRow []float64 for _, ele := range row { if num, err = strconv.ParseFloat(ele.String, 64); err != nil { return newErrorFormulaArg(formulaErrorVALUE, err.Error()) @@ -4783,9 +4784,9 @@ func (fn *formulaFuncs) STDEVA(argsList *list.List) formulaArg { // calcStdevPow is part of the implementation stdev. func calcStdevPow(result, count float64, n, m formulaArg) (float64, float64) { if result == -1 { - result = math.Pow((n.Number - m.Number), 2) + result = math.Pow(n.Number-m.Number, 2) } else { - result += math.Pow((n.Number - m.Number), 2) + result += math.Pow(n.Number-m.Number, 2) } count++ return result, count @@ -4985,7 +4986,8 @@ func (fn *formulaFuncs) SUMIFS(argsList *list.List) formulaArg { if argsList.Len()%2 != 1 { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } - sum, sumRange, args := 0.0, argsList.Front().Value.(formulaArg).Matrix, []formulaArg{} + var args []formulaArg + sum, sumRange := 0.0, argsList.Front().Value.(formulaArg).Matrix for arg := argsList.Front().Next(); arg != nil; arg = arg.Next() { args = append(args, arg.Value.(formulaArg)) } @@ -5260,7 +5262,7 @@ func (fn *formulaFuncs) AVEDEV(argsList *list.List) formulaArg { // AVERAGE(number1,[number2],...) // func (fn *formulaFuncs) AVERAGE(argsList *list.List) formulaArg { - args := []formulaArg{} + var args []formulaArg for arg := argsList.Front(); arg != nil; arg = arg.Next() { args = append(args, arg.Value.(formulaArg)) } @@ -5277,7 +5279,7 @@ func (fn *formulaFuncs) AVERAGE(argsList *list.List) formulaArg { // AVERAGEA(number1,[number2],...) // func (fn *formulaFuncs) AVERAGEA(argsList *list.List) formulaArg { - args := []formulaArg{} + var args []formulaArg for arg := argsList.Front(); arg != nil; arg = arg.Next() { args = append(args, arg.Value.(formulaArg)) } @@ -5353,7 +5355,8 @@ func (fn *formulaFuncs) AVERAGEIFS(argsList *list.List) formulaArg { if argsList.Len()%2 != 1 { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } - sum, sumRange, args := 0.0, argsList.Front().Value.(formulaArg).Matrix, []formulaArg{} + var args []formulaArg + sum, sumRange := 0.0, argsList.Front().Value.(formulaArg).Matrix for arg := argsList.Front().Next(); arg != nil; arg = arg.Next() { args = append(args, arg.Value.(formulaArg)) } @@ -5394,7 +5397,7 @@ func getBetaHelperContFrac(fX, fA, fB float64) float64 { if b2 != 0 { fnorm = 1 / b2 cfnew = a2 * fnorm - bfinished = (math.Abs(cf-cfnew) < math.Abs(cf)*fMachEps) + bfinished = math.Abs(cf-cfnew) < math.Abs(cf)*fMachEps } cf = cfnew rm += 1 @@ -5911,12 +5914,12 @@ func pbeta(x, pin, qin float64) (ans float64) { // betainvProbIterator is a part of betainv for the inverse of the beta // function. -func betainvProbIterator(alpha1, alpha3, beta1, beta2, beta3, logbeta, lower, maxCumulative, prob1, prob2, upper float64, needSwap bool) float64 { +func betainvProbIterator(alpha1, alpha3, beta1, beta2, beta3, logBeta, maxCumulative, prob1, prob2 float64) float64 { var i, j, prev, prop4 float64 j = 1 for prob := 0; prob < 1000; prob++ { prop3 := pbeta(beta3, alpha1, beta1) - prop3 = (prop3 - prob1) * math.Exp(logbeta+prob2*math.Log(beta3)+beta2*math.Log(1.0-beta3)) + prop3 = (prop3 - prob1) * math.Exp(logBeta+prob2*math.Log(beta3)+beta2*math.Log(1.0-beta3)) if prop3*prop4 <= 0 { prev = math.Max(math.Abs(j), maxCumulative) } @@ -5959,7 +5962,7 @@ func calcBetainv(probability, alpha, beta, lower, upper float64) float64 { } else { prob1, alpha1, beta1, needSwap = 1.0-probability, beta, alpha, true } - logbeta := logBeta(alpha, beta) + logBetaNum := logBeta(alpha, beta) prob2 := math.Sqrt(-math.Log(prob1 * prob1)) prob3 := prob2 - (prob2*0.27061+2.3075)/(prob2*(prob2*0.04481+0.99229)+1) if alpha1 > 1 && beta1 > 1 { @@ -5971,11 +5974,11 @@ func calcBetainv(probability, alpha, beta, lower, upper float64) float64 { beta2, prob2 = 1/(beta1*9), beta1+beta1 beta2 = prob2 * math.Pow(1-beta2+prob3*math.Sqrt(beta2), 3) if beta2 <= 0 { - beta3 = 1 - math.Exp((math.Log((1-prob1)*beta1)+logbeta)/beta1) + beta3 = 1 - math.Exp((math.Log((1-prob1)*beta1)+logBetaNum)/beta1) } else { beta2 = (prob2 + alpha1*4 - 2) / beta2 if beta2 <= 1 { - beta3 = math.Exp((logbeta + math.Log(alpha1*prob1)) / alpha1) + beta3 = math.Exp((logBetaNum + math.Log(alpha1*prob1)) / alpha1) } else { beta3 = 1 - 2/(beta2+1) } @@ -5988,7 +5991,7 @@ func calcBetainv(probability, alpha, beta, lower, upper float64) float64 { beta3 = upperBound } alpha3 := math.Max(minCumulative, math.Pow(10.0, -13.0-2.5/(alpha1*alpha1)-0.5/(prob1*prob1))) - beta3 = betainvProbIterator(alpha1, alpha3, beta1, beta2, beta3, logbeta, lower, maxCumulative, prob1, prob2, upper, needSwap) + beta3 = betainvProbIterator(alpha1, alpha3, beta1, beta2, beta3, logBetaNum, maxCumulative, prob1, prob2) if needSwap { beta3 = 1.0 - beta3 } @@ -6066,19 +6069,19 @@ func incompleteGamma(a, x float64) float64 { for n := 0; n <= max; n++ { divisor := a for i := 1; i <= n; i++ { - divisor *= (a + float64(i)) + divisor *= a + float64(i) } summer += math.Pow(x, float64(n)) / divisor } return math.Pow(x, a) * math.Exp(0-x) * summer } -// binomCoeff implement binomial coefficient calcuation. +// binomCoeff implement binomial coefficient calculation. func binomCoeff(n, k float64) float64 { return fact(n) / (fact(k) * fact(n-k)) } -// binomdist implement binomial distribution calcuation. +// binomdist implement binomial distribution calculation. func binomdist(x, n, p float64) float64 { return binomCoeff(n, x) * math.Pow(p, x) * math.Pow(1-p, n-x) } @@ -6176,11 +6179,11 @@ func (fn *formulaFuncs) BINOMdotDISTdotRANGE(argsList *list.List) formulaArg { if num2.Number < 0 || num2.Number > trials.Number { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } - sumn := 0.0 + sum := 0.0 for i := num1.Number; i <= num2.Number; i++ { - sumn += binomdist(i, trials.Number, probability.Number) + sum += binomdist(i, trials.Number, probability.Number) } - return newNumberFormulaArg(sumn) + return newNumberFormulaArg(sum) } // binominv implement inverse of the binomial distribution calcuation. @@ -6261,7 +6264,7 @@ func (fn *formulaFuncs) CHIDIST(argsList *list.List) formulaArg { // CHIINV function calculates the inverse of the right-tailed probability of // the Chi-Square Distribution. The syntax of the function is: // -// CHIINV(probability,degrees_freedom) +// CHIINV(probability,deg_freedom) // func (fn *formulaFuncs) CHIINV(argsList *list.List) formulaArg { if argsList.Len() != 2 { @@ -6274,14 +6277,14 @@ func (fn *formulaFuncs) CHIINV(argsList *list.List) formulaArg { if probability.Number <= 0 || probability.Number > 1 { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } - degress := argsList.Back().Value.(formulaArg).ToNumber() - if degress.Type != ArgNumber { - return degress + deg := argsList.Back().Value.(formulaArg).ToNumber() + if deg.Type != ArgNumber { + return deg } - if degress.Number < 1 { + if deg.Number < 1 { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } - return newNumberFormulaArg(gammainv(1-probability.Number, 0.5*degress.Number, 2.0)) + return newNumberFormulaArg(gammainv(1-probability.Number, 0.5*deg.Number, 2.0)) } // confidence is an implementation of the formula functions CONFIDENCE and @@ -6321,7 +6324,7 @@ func (fn *formulaFuncs) confidence(name string, argsList *list.List) formulaArg // CONFIDENCE function uses a Normal Distribution to calculate a confidence // value that can be used to construct the Confidence Interval for a -// population mean, for a supplied probablity and sample size. It is assumed +// population mean, for a supplied probability and sample size. It is assumed // that the standard deviation of the population is known. The syntax of the // function is: // @@ -6333,7 +6336,7 @@ func (fn *formulaFuncs) CONFIDENCE(argsList *list.List) formulaArg { // CONFIDENCEdotNORM function uses a Normal Distribution to calculate a // confidence value that can be used to construct the confidence interval for -// a population mean, for a supplied probablity and sample size. It is +// a population mean, for a supplied probability and sample size. It is // assumed that the standard deviation of the population is known. The syntax // of the Confidence.Norm function is: // @@ -6574,7 +6577,7 @@ func (fn *formulaFuncs) COUNTIF(argsList *list.List) formulaArg { // formulaIfsMatch function returns cells reference array which match criteria. func formulaIfsMatch(args []formulaArg) (cellRefs []cellRef) { for i := 0; i < len(args)-1; i += 2 { - match := []cellRef{} + var match []cellRef matrix, criteria := args[i].Matrix, formulaCriteriaParser(args[i+1].Value()) if i == 0 { for rowIdx, row := range matrix { @@ -6612,7 +6615,7 @@ func (fn *formulaFuncs) COUNTIFS(argsList *list.List) formulaArg { if argsList.Len()%2 != 0 { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } - args := []formulaArg{} + var args []formulaArg for arg := argsList.Front(); arg != nil; arg = arg.Next() { args = append(args, arg.Value.(formulaArg)) } @@ -6787,7 +6790,7 @@ func (fn *formulaFuncs) GAMMADIST(argsList *list.List) formulaArg { if cumulative.Number == 1 { return newNumberFormulaArg(incompleteGamma(alpha.Number, x.Number/beta.Number) / math.Gamma(alpha.Number)) } - return newNumberFormulaArg((1 / (math.Pow(beta.Number, alpha.Number) * math.Gamma(alpha.Number))) * math.Pow(x.Number, (alpha.Number-1)) * math.Exp(0-(x.Number/beta.Number))) + return newNumberFormulaArg((1 / (math.Pow(beta.Number, alpha.Number) * math.Gamma(alpha.Number))) * math.Pow(x.Number, alpha.Number-1) * math.Exp(0-(x.Number/beta.Number))) } // gammainv returns the inverse of the Gamma distribution for the specified @@ -6797,17 +6800,17 @@ func gammainv(probability, alpha, beta float64) float64 { dx, x, xNew, result := 1024.0, 1.0, 1.0, 0.0 for i := 0; math.Abs(dx) > 8.88e-016 && i <= 256; i++ { result = incompleteGamma(alpha, x/beta) / math.Gamma(alpha) - error := result - probability - if error == 0 { + e := result - probability + if e == 0 { dx = 0 - } else if error < 0 { + } else if e < 0 { xLo = x } else { xHi = x } - pdf := (1 / (math.Pow(beta, alpha) * math.Gamma(alpha))) * math.Pow(x, (alpha-1)) * math.Exp(0-(x/beta)) + pdf := (1 / (math.Pow(beta, alpha) * math.Gamma(alpha))) * math.Pow(x, alpha-1) * math.Exp(0-(x/beta)) if pdf != 0 { - dx = error / pdf + dx = e / pdf xNew = x - dx } if xNew < xLo || xNew > xHi || pdf == 0 { @@ -6925,7 +6928,7 @@ func (fn *formulaFuncs) GEOMEAN(argsList *list.List) formulaArg { count := fn.COUNT(argsList) min := fn.MIN(argsList) if product.Number > 0 && min.Number > 0 { - return newNumberFormulaArg(math.Pow(product.Number, (1 / count.Number))) + return newNumberFormulaArg(math.Pow(product.Number, 1/count.Number)) } return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } @@ -6958,7 +6961,7 @@ func (fn *formulaFuncs) HARMEAN(argsList *list.List) formulaArg { if number <= 0 { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } - val += (1 / number) + val += 1 / number cnt++ } return newNumberFormulaArg(1 / (val / cnt)) @@ -7206,7 +7209,7 @@ func (fn *formulaFuncs) LOGNORMdotDIST(argsList *list.List) formulaArg { return fn.NORMDIST(args) } return newNumberFormulaArg((1 / (math.Sqrt(2*math.Pi) * stdDev.Number * x.Number)) * - math.Exp(0-(math.Pow((math.Log(x.Number)-mean.Number), 2)/(2*math.Pow(stdDev.Number, 2))))) + math.Exp(0-(math.Pow(math.Log(x.Number)-mean.Number, 2)/(2*math.Pow(stdDev.Number, 2))))) } // LOGNORMDIST function calculates the Cumulative Log-Normal Distribution @@ -7455,7 +7458,7 @@ func (fn *formulaFuncs) kth(name string, argsList *list.List) formulaArg { if k < 1 { return newErrorFormulaArg(formulaErrorNUM, "k should be > 0") } - data := []float64{} + var data []float64 for _, arg := range array { if numArg := arg.ToNumber(); numArg.Type == ArgNumber { data = append(data, numArg.Number) @@ -7519,7 +7522,8 @@ func (fn *formulaFuncs) MAXIFS(argsList *list.List) formulaArg { if argsList.Len()%2 != 1 { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } - max, maxRange, args := -math.MaxFloat64, argsList.Front().Value.(formulaArg).Matrix, []formulaArg{} + var args []formulaArg + max, maxRange := -math.MaxFloat64, argsList.Front().Value.(formulaArg).Matrix for arg := argsList.Front().Next(); arg != nil; arg = arg.Next() { args = append(args, arg.Value.(formulaArg)) } @@ -7606,7 +7610,7 @@ func (fn *formulaFuncs) MEDIAN(argsList *list.List) formulaArg { if argsList.Len() == 0 { return newErrorFormulaArg(formulaErrorVALUE, "MEDIAN requires at least 1 argument") } - values := []float64{} + var values []float64 var median, digits float64 var err error for token := argsList.Front(); token != nil; token = token.Next() { @@ -7682,7 +7686,8 @@ func (fn *formulaFuncs) MINIFS(argsList *list.List) formulaArg { if argsList.Len()%2 != 1 { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } - min, minRange, args := math.MaxFloat64, argsList.Front().Value.(formulaArg).Matrix, []formulaArg{} + var args []formulaArg + min, minRange := math.MaxFloat64, argsList.Front().Value.(formulaArg).Matrix for arg := argsList.Front().Next(); arg != nil; arg = arg.Next() { args = append(args, arg.Value.(formulaArg)) } @@ -7778,7 +7783,7 @@ func (fn *formulaFuncs) PERCENTILEdotEXC(argsList *list.List) formulaArg { if k.Number <= 0 || k.Number >= 1 { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } - numbers := []float64{} + var numbers []float64 for _, arg := range array { if arg.Type == ArgError { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) @@ -7828,7 +7833,7 @@ func (fn *formulaFuncs) PERCENTILE(argsList *list.List) formulaArg { if k.Number < 0 || k.Number > 1 { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } - numbers := []float64{} + var numbers []float64 for _, arg := range array { if arg.Type == ArgError { return arg @@ -7861,7 +7866,7 @@ func (fn *formulaFuncs) percentrank(name string, argsList *list.List) formulaArg if x.Type != ArgNumber { return x } - numbers := []float64{} + var numbers []float64 for _, arg := range array { if arg.Type == ArgError { return arg @@ -7895,10 +7900,10 @@ func (fn *formulaFuncs) percentrank(name string, argsList *list.List) formulaArg pos-- pos += (x.Number - numbers[int(pos)]) / (cmp - numbers[int(pos)]) } - pow := math.Pow(10, float64(significance.Number)) - digit := pow * float64(pos) / (float64(cnt) - 1) + pow := math.Pow(10, significance.Number) + digit := pow * pos / (float64(cnt) - 1) if name == "PERCENTRANK.EXC" { - digit = pow * float64(pos+1) / (float64(cnt) + 1) + digit = pow * (pos + 1) / (float64(cnt) + 1) } return newNumberFormulaArg(math.Floor(digit) / pow) } @@ -8049,7 +8054,7 @@ func (fn *formulaFuncs) rank(name string, argsList *list.List) formulaArg { if num.Type != ArgNumber { return num } - arr := []float64{} + var arr []float64 for _, arg := range argsList.Front().Next().Value.(formulaArg).ToList() { n := arg.ToNumber() if n.Type == ArgNumber { @@ -8072,7 +8077,7 @@ func (fn *formulaFuncs) rank(name string, argsList *list.List) formulaArg { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } -// RANK.EQ function returns the statistical rank of a given value, within a +// RANKdotEQ function returns the statistical rank of a given value, within a // supplied array of values. If there are duplicate values in the list, these // are given the same rank. The syntax of the function is: // @@ -8212,7 +8217,7 @@ func (fn *formulaFuncs) TRIMMEAN(argsList *list.List) formulaArg { if percent.Number < 0 || percent.Number >= 1 { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } - arr := []float64{} + var arr []float64 arrArg := argsList.Front().Value.(formulaArg).ToList() for _, cell := range arrArg { num := cell.ToNumber() @@ -8254,14 +8259,14 @@ func (fn *formulaFuncs) vars(name string, argsList *list.List) formulaArg { for _, token := range arg.Value.(formulaArg).ToList() { num := token.ToNumber() if token.Value() != "TRUE" && num.Type == ArgNumber { - summerA += (num.Number * num.Number) + summerA += num.Number * num.Number summerB += num.Number count++ continue } num = token.ToBool() if num.Type == ArgNumber { - summerA += (num.Number * num.Number) + summerA += num.Number * num.Number summerB += num.Number count++ continue @@ -8352,10 +8357,10 @@ func (fn *formulaFuncs) WEIBULL(argsList *list.List) formulaArg { } cumulative := argsList.Back().Value.(formulaArg).ToBool() if cumulative.Boolean && cumulative.Number == 1 { - return newNumberFormulaArg(1 - math.Exp(0-math.Pow((x.Number/beta.Number), alpha.Number))) + return newNumberFormulaArg(1 - math.Exp(0-math.Pow(x.Number/beta.Number, alpha.Number))) } return newNumberFormulaArg((alpha.Number / math.Pow(beta.Number, alpha.Number)) * - math.Pow(x.Number, (alpha.Number-1)) * math.Exp(0-math.Pow((x.Number/beta.Number), alpha.Number))) + math.Pow(x.Number, alpha.Number-1) * math.Exp(0-math.Pow(x.Number/beta.Number, alpha.Number))) } return newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE) } @@ -8612,7 +8617,7 @@ func (fn *formulaFuncs) ISNA(argsList *list.List) formulaArg { return newStringFormulaArg(result) } -// ISNONTEXT function function tests if a supplied value is text. If not, the +// ISNONTEXT function tests if a supplied value is text. If not, the // function returns TRUE; If the supplied value is text, the function returns // FALSE. The syntax of the function is: // @@ -8630,7 +8635,7 @@ func (fn *formulaFuncs) ISNONTEXT(argsList *list.List) formulaArg { return newStringFormulaArg(result) } -// ISNUMBER function function tests if a supplied value is a number. If so, +// ISNUMBER function tests if a supplied value is a number. If so, // the function returns TRUE; Otherwise it returns FALSE. The syntax of the // function is: // @@ -8893,7 +8898,7 @@ func (fn *formulaFuncs) AND(argsList *list.List) formulaArg { return newBoolFormulaArg(and) } -// FALSE function function returns the logical value FALSE. The syntax of the +// FALSE function returns the logical value FALSE. The syntax of the // function is: // // FALSE() @@ -9221,16 +9226,16 @@ func (fn *formulaFuncs) DATEDIF(argsList *list.List) formulaArg { diff-- } case "m": - ydiff := ey - sy - mdiff := em - sm + yDiff := ey - sy + mDiff := em - sm if ed < sd { - mdiff-- + mDiff-- } - if mdiff < 0 { - ydiff-- - mdiff += 12 + if mDiff < 0 { + yDiff-- + mDiff += 12 } - diff = float64(ydiff*12 + mdiff) + diff = float64(yDiff*12 + mDiff) case "d", "md", "ym", "yd": diff = calcDateDif(unit, diff, []int{ey, sy, em, sm, ed, sd}, startArg, endArg) default: @@ -9242,8 +9247,8 @@ func (fn *formulaFuncs) DATEDIF(argsList *list.List) formulaArg { // isDateOnlyFmt check if the given string matches date-only format regular expressions. func isDateOnlyFmt(dateString string) bool { for _, df := range dateOnlyFormats { - submatch := df.FindStringSubmatch(dateString) - if len(submatch) > 1 { + subMatch := df.FindStringSubmatch(dateString) + if len(subMatch) > 1 { return true } } @@ -9253,8 +9258,8 @@ func isDateOnlyFmt(dateString string) bool { // isTimeOnlyFmt check if the given string matches time-only format regular expressions. func isTimeOnlyFmt(timeString string) bool { for _, tf := range timeFormats { - submatch := tf.FindStringSubmatch(timeString) - if len(submatch) > 1 { + subMatch := tf.FindStringSubmatch(timeString) + if len(subMatch) > 1 { return true } } @@ -9263,50 +9268,51 @@ func isTimeOnlyFmt(timeString string) bool { // strToTimePatternHandler1 parse and convert the given string in pattern // hh to the time. -func strToTimePatternHandler1(submatch []string) (h, m int, s float64, err error) { - h, err = strconv.Atoi(submatch[0]) +func strToTimePatternHandler1(subMatch []string) (h, m int, s float64, err error) { + h, err = strconv.Atoi(subMatch[0]) return } // strToTimePatternHandler2 parse and convert the given string in pattern // hh:mm to the time. -func strToTimePatternHandler2(submatch []string) (h, m int, s float64, err error) { - if h, err = strconv.Atoi(submatch[0]); err != nil { +func strToTimePatternHandler2(subMatch []string) (h, m int, s float64, err error) { + if h, err = strconv.Atoi(subMatch[0]); err != nil { return } - m, err = strconv.Atoi(submatch[2]) + m, err = strconv.Atoi(subMatch[2]) return } // strToTimePatternHandler3 parse and convert the given string in pattern // mm:ss to the time. -func strToTimePatternHandler3(submatch []string) (h, m int, s float64, err error) { - if m, err = strconv.Atoi(submatch[0]); err != nil { +func strToTimePatternHandler3(subMatch []string) (h, m int, s float64, err error) { + if m, err = strconv.Atoi(subMatch[0]); err != nil { return } - s, err = strconv.ParseFloat(submatch[2], 64) + s, err = strconv.ParseFloat(subMatch[2], 64) return } // strToTimePatternHandler4 parse and convert the given string in pattern // hh:mm:ss to the time. -func strToTimePatternHandler4(submatch []string) (h, m int, s float64, err error) { - if h, err = strconv.Atoi(submatch[0]); err != nil { +func strToTimePatternHandler4(subMatch []string) (h, m int, s float64, err error) { + if h, err = strconv.Atoi(subMatch[0]); err != nil { return } - if m, err = strconv.Atoi(submatch[2]); err != nil { + if m, err = strconv.Atoi(subMatch[2]); err != nil { return } - s, err = strconv.ParseFloat(submatch[4], 64) + s, err = strconv.ParseFloat(subMatch[4], 64) return } // strToTime parse and convert the given string to the time. func strToTime(str string) (int, int, float64, bool, bool, formulaArg) { - pattern, submatch := "", []string{} + var subMatch []string + pattern := "" for key, tf := range timeFormats { - submatch = tf.FindStringSubmatch(str) - if len(submatch) > 1 { + subMatch = tf.FindStringSubmatch(str) + if len(subMatch) > 1 { pattern = key break } @@ -9314,24 +9320,24 @@ func strToTime(str string) (int, int, float64, bool, bool, formulaArg) { if pattern == "" { return 0, 0, 0, false, false, newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE) } - dateIsEmpty := submatch[1] == "" - submatch = submatch[49:] + dateIsEmpty := subMatch[1] == "" + subMatch = subMatch[49:] var ( - l = len(submatch) - last = submatch[l-1] + l = len(subMatch) + last = subMatch[l-1] am = last == "am" pm = last == "pm" hours, minutes int seconds float64 err error ) - if handler, ok := map[string]func(subsubmatch []string) (int, int, float64, error){ + if handler, ok := map[string]func(match []string) (int, int, float64, error){ "hh": strToTimePatternHandler1, "hh:mm": strToTimePatternHandler2, "mm:ss": strToTimePatternHandler3, "hh:mm:ss": strToTimePatternHandler4, }[pattern]; ok { - if hours, minutes, seconds, err = handler(submatch); err != nil { + if hours, minutes, seconds, err = handler(subMatch); err != nil { return 0, 0, 0, false, false, newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE) } } @@ -9352,55 +9358,55 @@ func strToTime(str string) (int, int, float64, bool, bool, formulaArg) { // strToDatePatternHandler1 parse and convert the given string in pattern // mm/dd/yy to the date. -func strToDatePatternHandler1(submatch []string) (int, int, int, bool, error) { +func strToDatePatternHandler1(subMatch []string) (int, int, int, bool, error) { var year, month, day int var err error - if month, err = strconv.Atoi(submatch[1]); err != nil { + if month, err = strconv.Atoi(subMatch[1]); err != nil { return 0, 0, 0, false, err } - if day, err = strconv.Atoi(submatch[3]); err != nil { + if day, err = strconv.Atoi(subMatch[3]); err != nil { return 0, 0, 0, false, err } - if year, err = strconv.Atoi(submatch[5]); err != nil { + if year, err = strconv.Atoi(subMatch[5]); err != nil { return 0, 0, 0, false, err } if year < 0 || year > 9999 || (year > 99 && year < 1900) { return 0, 0, 0, false, ErrParameterInvalid } - return formatYear(year), month, day, submatch[8] == "", err + return formatYear(year), month, day, subMatch[8] == "", err } // strToDatePatternHandler2 parse and convert the given string in pattern mm // dd, yy to the date. -func strToDatePatternHandler2(submatch []string) (int, int, int, bool, error) { +func strToDatePatternHandler2(subMatch []string) (int, int, int, bool, error) { var year, month, day int var err error - month = month2num[submatch[1]] - if day, err = strconv.Atoi(submatch[14]); err != nil { + month = month2num[subMatch[1]] + if day, err = strconv.Atoi(subMatch[14]); err != nil { return 0, 0, 0, false, err } - if year, err = strconv.Atoi(submatch[16]); err != nil { + if year, err = strconv.Atoi(subMatch[16]); err != nil { return 0, 0, 0, false, err } if year < 0 || year > 9999 || (year > 99 && year < 1900) { return 0, 0, 0, false, ErrParameterInvalid } - return formatYear(year), month, day, submatch[19] == "", err + return formatYear(year), month, day, subMatch[19] == "", err } // strToDatePatternHandler3 parse and convert the given string in pattern // yy-mm-dd to the date. -func strToDatePatternHandler3(submatch []string) (int, int, int, bool, error) { +func strToDatePatternHandler3(subMatch []string) (int, int, int, bool, error) { var year, month, day int - v1, err := strconv.Atoi(submatch[1]) + v1, err := strconv.Atoi(subMatch[1]) if err != nil { return 0, 0, 0, false, err } - v2, err := strconv.Atoi(submatch[3]) + v2, err := strconv.Atoi(subMatch[3]) if err != nil { return 0, 0, 0, false, err } - v3, err := strconv.Atoi(submatch[5]) + v3, err := strconv.Atoi(subMatch[5]) if err != nil { return 0, 0, 0, false, err } @@ -9415,30 +9421,31 @@ func strToDatePatternHandler3(submatch []string) (int, int, int, bool, error) { } else { return 0, 0, 0, false, ErrParameterInvalid } - return year, month, day, submatch[8] == "", err + return year, month, day, subMatch[8] == "", err } // strToDatePatternHandler4 parse and convert the given string in pattern // yy-mmStr-dd, yy to the date. -func strToDatePatternHandler4(submatch []string) (int, int, int, bool, error) { +func strToDatePatternHandler4(subMatch []string) (int, int, int, bool, error) { var year, month, day int var err error - if year, err = strconv.Atoi(submatch[16]); err != nil { + if year, err = strconv.Atoi(subMatch[16]); err != nil { return 0, 0, 0, false, err } - month = month2num[submatch[3]] - if day, err = strconv.Atoi(submatch[1]); err != nil { + month = month2num[subMatch[3]] + if day, err = strconv.Atoi(subMatch[1]); err != nil { return 0, 0, 0, false, err } - return formatYear(year), month, day, submatch[19] == "", err + return formatYear(year), month, day, subMatch[19] == "", err } // strToDate parse and convert the given string to the date. func strToDate(str string) (int, int, int, bool, formulaArg) { - pattern, submatch := "", []string{} + var subMatch []string + pattern := "" for key, df := range dateFormats { - submatch = df.FindStringSubmatch(str) - if len(submatch) > 1 { + subMatch = df.FindStringSubmatch(str) + if len(subMatch) > 1 { pattern = key break } @@ -9451,13 +9458,13 @@ func strToDate(str string) (int, int, int, bool, formulaArg) { year, month, day int err error ) - if handler, ok := map[string]func(subsubmatch []string) (int, int, int, bool, error){ + if handler, ok := map[string]func(match []string) (int, int, int, bool, error){ "mm/dd/yy": strToDatePatternHandler1, "mm dd, yy": strToDatePatternHandler2, "yy-mm-dd": strToDatePatternHandler3, "yy-mmStr-dd": strToDatePatternHandler4, }[pattern]; ok { - if year, month, day, timeIsEmpty, err = handler(submatch); err != nil { + if year, month, day, timeIsEmpty, err = handler(subMatch); err != nil { return 0, 0, 0, false, newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE) } } @@ -9469,8 +9476,8 @@ func strToDate(str string) (int, int, int, bool, formulaArg) { // DATEVALUE function converts a text representation of a date into an Excel // date. For example, the function converts a text string representing a -// date, into the serial number that represents the date in Excel's date-time -// code. The syntax of the function is: +// date, into the serial number that represents the date in Excels' date-time +// code. The syntax of the function is: // // DATEVALUE(date_text) // @@ -9553,7 +9560,7 @@ func (fn *formulaFuncs) ISOWEEKNUM(argsList *list.List) formulaArg { } date := argsList.Front().Value.(formulaArg) num := date.ToNumber() - weeknum := 0 + weekNum := 0 if num.Type != ArgNumber { dateString := strings.ToLower(date.Value()) if !isDateOnlyFmt(dateString) { @@ -9565,14 +9572,14 @@ func (fn *formulaFuncs) ISOWEEKNUM(argsList *list.List) formulaArg { if err.Type == ArgError { return err } - _, weeknum = time.Date(y, time.Month(m), d, 0, 0, 0, 0, time.UTC).ISOWeek() + _, weekNum = time.Date(y, time.Month(m), d, 0, 0, 0, 0, time.UTC).ISOWeek() } else { if num.Number < 0 { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } - _, weeknum = timeFromExcelTime(num.Number, false).ISOWeek() + _, weekNum = timeFromExcelTime(num.Number, false).ISOWeek() } - return newNumberFormulaArg(float64(weeknum)) + return newNumberFormulaArg(float64(weekNum)) } // HOUR function returns an integer representing the hour component of a @@ -9889,7 +9896,7 @@ func (fn *formulaFuncs) SECOND(argsList *list.List) formulaArg { // TIME function accepts three integer arguments representing hours, minutes // and seconds, and returns an Excel time. I.e. the function returns the -// decimal value that represents the time in Excel. The syntax of the Time +// decimal value that represents the time in Excel. The syntax of the // function is: // // TIME(hour,minute,second) @@ -9912,7 +9919,7 @@ func (fn *formulaFuncs) TIME(argsList *list.List) formulaArg { } // TIMEVALUE function converts a text representation of a time, into an Excel -// time. The syntax of the Timevalue function is: +// time. The syntax of the function is: // // TIMEVALUE(time_text) // @@ -10875,19 +10882,18 @@ func matchPattern(pattern, name string) (matched bool) { if pattern == "*" { return true } - rname, rpattern := make([]rune, 0, len(name)), make([]rune, 0, len(pattern)) + rName, rPattern := make([]rune, 0, len(name)), make([]rune, 0, len(pattern)) for _, r := range name { - rname = append(rname, r) + rName = append(rName, r) } for _, r := range pattern { - rpattern = append(rpattern, r) + rPattern = append(rPattern, r) } - simple := false // Does extended wildcard '*' and '?' match. - return deepMatchRune(rname, rpattern, simple) + return deepMatchRune(rName, rPattern, false) } -// compareFormulaArg compares the left-hand sides and the right-hand sides -// formula arguments by given conditions such as case sensitive, if exact +// compareFormulaArg compares the left-hand sides and the right-hand sides' +// formula arguments by given conditions such as case-sensitive, if exact // match, and make compare result as formula criteria condition type. func compareFormulaArg(lhs, rhs, matchMode formulaArg, caseSensitive bool) byte { if lhs.Type != rhs.Type { @@ -10941,7 +10947,7 @@ func compareFormulaArgList(lhs, rhs, matchMode formulaArg, caseSensitive bool) b return criteriaEq } -// compareFormulaArgMatrix compares the left-hand sides and the right-hand sides +// compareFormulaArgMatrix compares the left-hand sides and the right-hand sides' // matrix type formula arguments. func compareFormulaArgMatrix(lhs, rhs, matchMode formulaArg, caseSensitive bool) byte { if len(lhs.Matrix) < len(rhs.Matrix) { @@ -11267,7 +11273,7 @@ func (fn *formulaFuncs) TRANSPOSE(argsList *list.List) formulaArg { // lookupLinearSearch sequentially checks each look value of the lookup array until // a match is found or the whole list has been searched. func lookupLinearSearch(vertical bool, lookupValue, lookupArray, matchMode, searchMode formulaArg) (int, bool) { - tableArray := []formulaArg{} + var tableArray []formulaArg if vertical { for _, row := range lookupArray.Matrix { tableArray = append(tableArray, row[0]) @@ -11336,7 +11342,7 @@ func (fn *formulaFuncs) VLOOKUP(argsList *list.List) formulaArg { // is TRUE, if the data of table array can't guarantee be sorted, it will // return wrong result. func lookupBinarySearch(vertical bool, lookupValue, lookupArray, matchMode, searchMode formulaArg) (matchIdx int, wasExact bool) { - tableArray := []formulaArg{} + var tableArray []formulaArg if vertical { for _, row := range lookupArray.Matrix { tableArray = append(tableArray, row[0]) @@ -11344,7 +11350,7 @@ func lookupBinarySearch(vertical bool, lookupValue, lookupArray, matchMode, sear } else { tableArray = lookupArray.Matrix[0] } - var low, high, lastMatchIdx int = 0, len(tableArray) - 1, -1 + var low, high, lastMatchIdx = 0, len(tableArray) - 1, -1 count := high for low <= high { mid := low + (high-low)/2 @@ -11425,7 +11431,7 @@ func iterateLookupArgs(lookupValue, lookupVector formulaArg) ([]formulaArg, int, matchIdx = idx break } - // Find nearest match if lookup value is more than or equal to the first value in lookup vector + // Find the nearest match if lookup value is more than or equal to the first value in lookup vector if idx == 0 { ok = compare == criteriaG } else if ok && compare == criteriaL && matchIdx == -1 { @@ -11447,7 +11453,7 @@ func (fn *formulaFuncs) index(array formulaArg, rowIdx, colIdx int) formulaArg { if colIdx >= len(cellMatrix[0]) { return newErrorFormulaArg(formulaErrorREF, "INDEX col_num out of range") } - column := [][]formulaArg{} + var column [][]formulaArg for _, cells = range cellMatrix { column = append(column, []formulaArg{cells[colIdx]}) } @@ -11513,7 +11519,7 @@ func (fn *formulaFuncs) prepareXlookupArgs(argsList *list.List) formulaArg { func (fn *formulaFuncs) xlookup(lookupRows, lookupCols, returnArrayRows, returnArrayCols, matchIdx int, condition1, condition2, condition3, condition4 bool, returnArray formulaArg, ) formulaArg { - result := [][]formulaArg{} + var result [][]formulaArg for rowIdx, row := range returnArray.Matrix { for colIdx, cell := range row { if condition1 { @@ -12105,7 +12111,7 @@ func is30BasisMethod(basis int) bool { // getDaysInMonthRange return the day by given year, month range and day count // basis. -func getDaysInMonthRange(year, fromMonth, toMonth, basis int) int { +func getDaysInMonthRange(fromMonth, toMonth int) int { if fromMonth > toMonth { return 0 } @@ -12153,10 +12159,10 @@ func coupdays(from, to time.Time, basis int) float64 { fromDay = 1 date := time.Date(fromY, fromM, fromD, 0, 0, 0, 0, time.UTC).AddDate(0, 1, 0) if date.Year() < toY { - days += getDaysInMonthRange(date.Year(), int(date.Month()), 12, basis) + days += getDaysInMonthRange(int(date.Month()), 12) date = date.AddDate(0, 13-int(date.Month()), 0) } - days += getDaysInMonthRange(toY, int(date.Month()), int(toM)-1, basis) + days += getDaysInMonthRange(int(date.Month()), int(toM)-1) } if days += toDay - fromDay; days > 0 { return float64(days) @@ -12363,7 +12369,7 @@ func (fn *formulaFuncs) cumip(name string, argsList *list.List) formulaArg { return newNumberFormulaArg(num) } -// calcDbArgsCompare implements common arguments comparison for DB and DDB. +// calcDbArgsCompare implements common arguments' comparison for DB and DDB. func calcDbArgsCompare(cost, salvage, life, period formulaArg) bool { return (cost.Number <= 0) || ((salvage.Number / cost.Number) < 0) || (life.Number <= 0) || (period.Number < 1) } @@ -12468,7 +12474,7 @@ func (fn *formulaFuncs) DDB(argsList *list.List) formulaArg { } pd, depreciation := 0.0, 0.0 for per := 1; per <= int(period.Number); per++ { - depreciation = math.Min((cost.Number-pd)*(factor.Number/life.Number), (cost.Number - salvage.Number - pd)) + depreciation = math.Min((cost.Number-pd)*(factor.Number/life.Number), cost.Number-salvage.Number-pd) pd += depreciation } return newNumberFormulaArg(depreciation) @@ -12478,7 +12484,7 @@ func (fn *formulaFuncs) DDB(argsList *list.List) formulaArg { // formula functions. func (fn *formulaFuncs) prepareDataValueArgs(n int, argsList *list.List) formulaArg { l := list.New() - dataValues := []formulaArg{} + var dataValues []formulaArg getDateValue := func(arg formulaArg, l *list.List) formulaArg { switch arg.Type { case ArgNumber: @@ -12715,7 +12721,7 @@ func (fn *formulaFuncs) EFFECT(argsList *list.List) formulaArg { if rate.Number <= 0 || npery.Number < 1 { return newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM) } - return newNumberFormulaArg(math.Pow((1+rate.Number/npery.Number), npery.Number) - 1) + return newNumberFormulaArg(math.Pow(1+rate.Number/npery.Number, npery.Number) - 1) } // FV function calculates the Future Value of an investment with periodic @@ -12785,7 +12791,7 @@ func (fn *formulaFuncs) FVSCHEDULE(argsList *list.List) formulaArg { if rate.Type != ArgNumber { return rate } - principal *= (1 + rate.Number) + principal *= 1 + rate.Number } return newNumberFormulaArg(principal) } @@ -12945,7 +12951,7 @@ func (fn *formulaFuncs) IRR(argsList *list.List) formulaArg { if f1.Number*f2.Number < 0 { break } - if math.Abs(f1.Number) < math.Abs((f2.Number)) { + if math.Abs(f1.Number) < math.Abs(f2.Number) { x1.Number += 1.6 * (x1.Number - x2.Number) args.Front().Value = x1 f1 = fn.NPV(args) @@ -13061,10 +13067,10 @@ func (fn *formulaFuncs) MIRR(argsList *list.List) formulaArg { for i, v := range values { val := v.ToNumber() if val.Number >= 0 { - npvPos += val.Number / math.Pow(float64(rr), float64(i)) + npvPos += val.Number / math.Pow(rr, float64(i)) continue } - npvNeg += val.Number / math.Pow(float64(fr), float64(i)) + npvNeg += val.Number / math.Pow(fr, float64(i)) } if npvNeg == 0 || npvPos == 0 || reinvestRate.Number <= -1 { return newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV) @@ -13173,7 +13179,7 @@ func (fn *formulaFuncs) NPV(argsList *list.List) formulaArg { // aggrBetween is a part of implementation of the formula function ODDFPRICE. func aggrBetween(startPeriod, endPeriod float64, initialValue []float64, f func(acc []float64, index float64) []float64) []float64 { - s := []float64{} + var s []float64 if startPeriod <= endPeriod { for i := startPeriod; i <= endPeriod; i++ { s = append(s, i) @@ -13211,7 +13217,7 @@ func changeMonth(date time.Time, numMonths float64, returnLastMonth bool) time.T // datesAggregate is a part of implementation of the formula function // ODDFPRICE. -func datesAggregate(startDate, endDate time.Time, numMonths, basis float64, f func(pcd, ncd time.Time) float64, acc float64, returnLastMonth bool) (time.Time, time.Time, float64) { +func datesAggregate(startDate, endDate time.Time, numMonths float64, f func(pcd, ncd time.Time) float64, acc float64, returnLastMonth bool) (time.Time, time.Time, float64) { frontDate, trailingDate := startDate, endDate s1 := frontDate.After(endDate) || frontDate.Equal(endDate) s2 := endDate.After(frontDate) || endDate.Equal(frontDate) @@ -13235,7 +13241,7 @@ func datesAggregate(startDate, endDate time.Time, numMonths, basis float64, f fu } // coupNumber is a part of implementation of the formula function ODDFPRICE. -func coupNumber(maturity, settlement, numMonths, basis float64) float64 { +func coupNumber(maturity, settlement, numMonths float64) float64 { maturityTime, settlementTime := timeFromExcelTime(maturity, false), timeFromExcelTime(settlement, false) my, mm, md := maturityTime.Year(), maturityTime.Month(), maturityTime.Day() sy, sm, sd := settlementTime.Year(), settlementTime.Month(), settlementTime.Day() @@ -13253,7 +13259,7 @@ func coupNumber(maturity, settlement, numMonths, basis float64) float64 { f := func(pcd, ncd time.Time) float64 { return 1 } - _, _, result := datesAggregate(date, maturityTime, numMonths, basis, f, coupons, endOfMonth) + _, _, result := datesAggregate(date, maturityTime, numMonths, f, coupons, endOfMonth) return result } @@ -13338,7 +13344,7 @@ func (fn *formulaFuncs) ODDFPRICE(argsList *list.List) formulaArg { numMonths := 12 / frequency.Number numMonthsNeg := -numMonths mat := changeMonth(maturityTime, numMonthsNeg, returnLastMonth) - pcd, _, _ := datesAggregate(mat, firstCouponTime, numMonthsNeg, basisArg.Number, func(d1, d2 time.Time) float64 { + pcd, _, _ := datesAggregate(mat, firstCouponTime, numMonthsNeg, func(d1, d2 time.Time) float64 { return 0 }, 0, returnLastMonth) if !pcd.Equal(firstCouponTime) { @@ -13419,7 +13425,7 @@ func (fn *formulaFuncs) ODDFPRICE(argsList *list.List) formulaArg { a := coupdays(d, settlementTime, basis) dsc = e.Number - a } - nq := coupNumber(firstCoupon.Number, settlement.Number, numMonths, basisArg.Number) + nq := coupNumber(firstCoupon.Number, settlement.Number, numMonths) fnArgs.Init() fnArgs.PushBack(firstCoupon) fnArgs.PushBack(maturity) @@ -13508,7 +13514,7 @@ func (fn *formulaFuncs) PMT(argsList *list.List) formulaArg { return newErrorFormulaArg(formulaErrorNA, formulaErrorNA) } if rate.Number != 0 { - p := (-fv.Number - pv.Number*math.Pow((1+rate.Number), nper.Number)) / (1 + rate.Number*typ.Number) / ((math.Pow((1+rate.Number), nper.Number) - 1) / rate.Number) + p := (-fv.Number - pv.Number*math.Pow(1+rate.Number, nper.Number)) / (1 + rate.Number*typ.Number) / ((math.Pow(1+rate.Number, nper.Number) - 1) / rate.Number) return newNumberFormulaArg(p) } return newNumberFormulaArg((-pv.Number - fv.Number) / nper.Number) @@ -13747,9 +13753,9 @@ func (fn *formulaFuncs) PV(argsList *list.List) formulaArg { } // rate is an implementation of the formula function RATE. -func (fn *formulaFuncs) rate(nper, pmt, pv, fv, t, guess formulaArg, argsList *list.List) formulaArg { - maxIter, iter, close, epsMax, rate := 100, 0, false, 1e-6, guess.Number - for iter < maxIter && !close { +func (fn *formulaFuncs) rate(nper, pmt, pv, fv, t, guess formulaArg) formulaArg { + maxIter, iter, isClose, epsMax, rate := 100, 0, false, 1e-6, guess.Number + for iter < maxIter && !isClose { t1 := math.Pow(rate+1, nper.Number) t2 := math.Pow(rate+1, nper.Number-1) rt := rate*t.Number + 1 @@ -13761,7 +13767,7 @@ func (fn *formulaFuncs) rate(nper, pmt, pv, fv, t, guess formulaArg, argsList *l f3 := (nper.Number*pmt.Number*t2*rt + p0*t.Number) / rate delta := f1 / (f2 + f3) if math.Abs(delta) < epsMax { - close = true + isClose = true } iter++ rate -= delta @@ -13815,7 +13821,7 @@ func (fn *formulaFuncs) RATE(argsList *list.List) formulaArg { return guess } } - return fn.rate(nper, pmt, pv, fv, t, guess, argsList) + return fn.rate(nper, pmt, pv, fv, t, guess) } // RECEIVED function calculates the amount received at maturity for a fully @@ -14159,7 +14165,7 @@ func (fn *formulaFuncs) VDB(argsList *list.List) formulaArg { } // prepareXArgs prepare arguments for the formula function XIRR and XNPV. -func (fn *formulaFuncs) prepareXArgs(name string, values, dates formulaArg) (valuesArg, datesArg []float64, err formulaArg) { +func (fn *formulaFuncs) prepareXArgs(values, dates formulaArg) (valuesArg, datesArg []float64, err formulaArg) { for _, arg := range values.ToList() { if numArg := arg.ToNumber(); numArg.Type == ArgNumber { valuesArg = append(valuesArg, numArg.Number) @@ -14267,7 +14273,7 @@ func (fn *formulaFuncs) XIRR(argsList *list.List) formulaArg { if argsList.Len() != 2 && argsList.Len() != 3 { return newErrorFormulaArg(formulaErrorVALUE, "XIRR requires 2 or 3 arguments") } - values, dates, err := fn.prepareXArgs("XIRR", argsList.Front().Value.(formulaArg), argsList.Front().Next().Value.(formulaArg)) + values, dates, err := fn.prepareXArgs(argsList.Front().Value.(formulaArg), argsList.Front().Next().Value.(formulaArg)) if err.Type != ArgEmpty { return err } @@ -14299,7 +14305,7 @@ func (fn *formulaFuncs) XNPV(argsList *list.List) formulaArg { if rate.Number <= 0 { return newErrorFormulaArg(formulaErrorVALUE, "XNPV requires rate > 0") } - values, dates, err := fn.prepareXArgs("XNPV", argsList.Front().Next().Value.(formulaArg), argsList.Back().Value.(formulaArg)) + values, dates, err := fn.prepareXArgs(argsList.Front().Next().Value.(formulaArg), argsList.Back().Value.(formulaArg)) if err.Type != ArgEmpty { return err } diff --git a/calc_test.go b/calc_test.go index 4025cec..6708cdb 100644 --- a/calc_test.go +++ b/calc_test.go @@ -4629,7 +4629,7 @@ func TestCalcLogBeta(t *testing.T) { } func TestCalcBetainvProbIterator(t *testing.T) { - assert.Equal(t, 1.0, betainvProbIterator(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, true)) + assert.Equal(t, 1.0, betainvProbIterator(1, 1, 1, 1, 1, 1, 1, 1, 1)) } func TestNestedFunctionsWithOperators(t *testing.T) { diff --git a/cell.go b/cell.go index 6ecce4f..4b76271 100644 --- a/cell.go +++ b/cell.go @@ -200,7 +200,7 @@ func (f *File) setCellTimeFunc(sheet, axis string, value time.Time) error { if err != nil { return err } - cellData, col, row, err := f.prepareCell(ws, sheet, axis) + cellData, col, row, err := f.prepareCell(ws, axis) if err != nil { return err } @@ -251,7 +251,7 @@ func (f *File) SetCellInt(sheet, axis string, value int) error { if err != nil { return err } - cellData, col, row, err := f.prepareCell(ws, sheet, axis) + cellData, col, row, err := f.prepareCell(ws, axis) if err != nil { return err } @@ -276,7 +276,7 @@ func (f *File) SetCellBool(sheet, axis string, value bool) error { if err != nil { return err } - cellData, col, row, err := f.prepareCell(ws, sheet, axis) + cellData, col, row, err := f.prepareCell(ws, axis) if err != nil { return err } @@ -299,7 +299,7 @@ func setCellBool(value bool) (t string, v string) { return } -// SetCellFloat sets a floating point value into a cell. The prec parameter +// SetCellFloat sets a floating point value into a cell. The precision parameter // specifies how many places after the decimal will be shown while -1 is a // special value that will use as many decimal places as necessary to // represent the number. bitSize is 32 or 64 depending on if a float32 or @@ -308,26 +308,26 @@ func setCellBool(value bool) (t string, v string) { // var x float32 = 1.325 // f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32) // -func (f *File) SetCellFloat(sheet, axis string, value float64, prec, bitSize int) error { +func (f *File) SetCellFloat(sheet, axis string, value float64, precision, bitSize int) error { ws, err := f.workSheetReader(sheet) if err != nil { return err } - cellData, col, row, err := f.prepareCell(ws, sheet, axis) + cellData, col, row, err := f.prepareCell(ws, axis) if err != nil { return err } ws.Lock() defer ws.Unlock() cellData.S = f.prepareCellStyle(ws, col, row, cellData.S) - cellData.T, cellData.V = setCellFloat(value, prec, bitSize) + cellData.T, cellData.V = setCellFloat(value, precision, bitSize) return err } // setCellFloat prepares cell type and string type cell value by a given // float value. -func setCellFloat(value float64, prec, bitSize int) (t string, v string) { - v = strconv.FormatFloat(value, 'f', prec, bitSize) +func setCellFloat(value float64, precision, bitSize int) (t string, v string) { + v = strconv.FormatFloat(value, 'f', precision, bitSize) return } @@ -338,7 +338,7 @@ func (f *File) SetCellStr(sheet, axis, value string) error { if err != nil { return err } - cellData, col, row, err := f.prepareCell(ws, sheet, axis) + cellData, col, row, err := f.prepareCell(ws, axis) if err != nil { return err } @@ -436,7 +436,7 @@ func (f *File) SetCellDefault(sheet, axis, value string) error { if err != nil { return err } - cellData, col, row, err := f.prepareCell(ws, sheet, axis) + cellData, col, row, err := f.prepareCell(ws, axis) if err != nil { return err } @@ -478,7 +478,7 @@ type FormulaOpts struct { } // SetCellFormula provides a function to set formula on the cell is taken -// according to the given worksheet name (case sensitive) and cell formula +// according to the given worksheet name (case-sensitive) and cell formula // settings. The result of the formula cell can be calculated when the // worksheet is opened by the Office Excel application or can be using // the "CalcCellValue" function also can get the calculated cell value. If @@ -560,7 +560,7 @@ func (f *File) SetCellFormula(sheet, axis, formula string, opts ...FormulaOpts) if err != nil { return err } - cellData, _, _, err := f.prepareCell(ws, sheet, axis) + cellData, _, _, err := f.prepareCell(ws, axis) if err != nil { return err } @@ -672,12 +672,9 @@ type HyperlinkOpts struct { // SetCellHyperLink provides a function to set cell hyperlink by given // worksheet name and link URL address. LinkType defines two types of -// hyperlink "External" for web site or "Location" for moving to one of cell -// in this workbook. Maximum limit hyperlinks in a worksheet is 65530. This -// function is only used to set the hyperlink of the cell and doesn't affect -// the value of the cell. If you need to set the value of the cell, please use -// the other functions such as `SetCellStyle` or `SetSheetRow`. The below is -// example for external link. +// hyperlink "External" for website or "Location" for moving to one of cell +// in this workbook. Maximum limit hyperlinks in a worksheet is 65530. The +// below is example for external link. // // if err := f.SetCellHyperLink("Sheet1", "A3", // "https://github.com/xuri/excelize", "External"); err != nil { @@ -692,7 +689,7 @@ type HyperlinkOpts struct { // } // err = f.SetCellStyle("Sheet1", "A3", "A3", style) // -// A this is another example for "Location": +// This is another example for "Location": // // err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location") // @@ -759,7 +756,7 @@ func (f *File) GetCellRichText(sheet, cell string) (runs []RichTextRun, err erro if err != nil { return } - cellData, _, _, err := f.prepareCell(ws, sheet, cell) + cellData, _, _, err := f.prepareCell(ws, cell) if err != nil { return } @@ -940,7 +937,7 @@ func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error { if err != nil { return err } - cellData, col, row, err := f.prepareCell(ws, sheet, cell) + cellData, col, row, err := f.prepareCell(ws, cell) if err != nil { return err } @@ -950,7 +947,7 @@ func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error { cellData.S = f.prepareCellStyle(ws, col, row, cellData.S) si := xlsxSI{} sst := f.sharedStringsReader() - textRuns := []xlsxR{} + var textRuns []xlsxR totalCellChars := 0 for _, textRun := range runs { totalCellChars += len(textRun.Text) @@ -1000,8 +997,8 @@ func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error { for i := 0; i < v.Len(); i++ { cell, err := CoordinatesToCellName(col+i, row) - // Error should never happens here. But keep checking to early detect regresions - // if it will be introduced in future. + // Error should never happen here. But keep checking to early detect regressions + // if it will be introduced in the future. if err != nil { return err } @@ -1013,7 +1010,7 @@ func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error { } // getCellInfo does common preparation for all SetCell* methods. -func (f *File) prepareCell(ws *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) { +func (f *File) prepareCell(ws *xlsxWorksheet, cell string) (*xlsxC, int, int, error) { var err error cell, err = f.mergeCellsParser(ws, cell) if err != nil { @@ -1175,7 +1172,7 @@ func (f *File) checkCellInArea(cell, area string) (bool, error) { return cellInRef([]int{col, row}, coordinates), err } -// cellInRef provides a function to determine if a given range is within an +// cellInRef provides a function to determine if a given range is within a // range. func cellInRef(cell, ref []int) bool { return cell[0] >= ref[0] && cell[0] <= ref[2] && cell[1] >= ref[1] && cell[1] <= ref[3] @@ -1241,7 +1238,7 @@ func parseSharedFormula(dCol, dRow int, orig []byte) (res string, start int) { // considered to be the same when their respective representations in // R1C1-reference notation, are the same. // -// Note that this function not validate ref tag to check the cell if or not in +// Note that this function not validate ref tag to check the cell whether in // allow area, and always return origin shared formula. func getSharedFormula(ws *xlsxWorksheet, si int, axis string) string { for _, r := range ws.SheetData.Row { @@ -1264,7 +1261,7 @@ func getSharedFormula(ws *xlsxWorksheet, si int, axis string) string { } // shiftCell returns the cell shifted according to dCol and dRow taking into -// consideration of absolute references with dollar sign ($) +// consideration absolute references with dollar sign ($) func shiftCell(cellID string, dCol, dRow int) string { fCol, fRow, _ := CellNameToCoordinates(cellID) signCol, signRow := "", "" diff --git a/cell_test.go b/cell_test.go index 92d3d2f..73b3018 100644 --- a/cell_test.go +++ b/cell_test.go @@ -33,7 +33,7 @@ func TestConcurrency(t *testing.T) { assert.NoError(t, f.SetSheetRow("Sheet1", "B6", &[]interface{}{ " Hello", []byte("World"), 42, int8(1<<8/2 - 1), int16(1<<16/2 - 1), int32(1<<32/2 - 1), - int64(1<<32/2 - 1), float32(42.65418), float64(-42.65418), float32(42), float64(42), + int64(1<<32/2 - 1), float32(42.65418), -42.65418, float32(42), float64(42), uint(1<<32 - 1), uint8(1<<8 - 1), uint16(1<<16 - 1), uint32(1<<32 - 1), uint64(1<<32 - 1), true, complex64(5 + 10i), })) diff --git a/chart.go b/chart.go index 4543770..8f521fa 100644 --- a/chart.go +++ b/chart.go @@ -969,7 +969,7 @@ func (f *File) AddChartSheet(sheet, format string, combo ...string) error { // getFormatChart provides a function to check format set of the chart and // create chart format. func (f *File) getFormatChart(format string, combo []string) (*formatChart, []*formatChart, error) { - comboCharts := []*formatChart{} + var comboCharts []*formatChart formatSet, err := parseFormatChartSet(format) if err != nil { return formatSet, comboCharts, err diff --git a/chart_test.go b/chart_test.go index b1b4791..9f2287e 100644 --- a/chart_test.go +++ b/chart_test.go @@ -353,7 +353,7 @@ func TestChartWithLogarithmicBase(t *testing.T) { } assert.True(t, ok, "Can't open the %s", chartPath) - err = xml.Unmarshal([]byte(xmlCharts[i]), &chartSpaces[i]) + err = xml.Unmarshal(xmlCharts[i], &chartSpaces[i]) if !assert.NoError(t, err) { t.FailNow() } diff --git a/col.go b/col.go index 827d727..ee1a407 100644 --- a/col.go +++ b/col.go @@ -40,8 +40,7 @@ type Cols struct { sheetXML []byte } -// GetCols return all the columns in a sheet by given worksheet name (case -// sensitive). For example: +// GetCols return all the columns in a sheet by given worksheet name (case-sensitive). For example: // // cols, err := f.GetCols("Sheet1") // if err != nil { @@ -240,20 +239,18 @@ func (f *File) Cols(sheet string) (*Cols, error) { // visible, err := f.GetColVisible("Sheet1", "D") // func (f *File) GetColVisible(sheet, col string) (bool, error) { - visible := true colNum, err := ColumnNameToNumber(col) if err != nil { - return visible, err + return true, err } - ws, err := f.workSheetReader(sheet) if err != nil { return false, err } if ws.Cols == nil { - return visible, err + return true, err } - + visible := true for c := range ws.Cols.Col { colData := &ws.Cols.Col[c] if colData.Min <= colNum && colNum <= colData.Max { @@ -455,12 +452,12 @@ func (f *File) SetColStyle(sheet, columns string, styleID int) error { // f := excelize.NewFile() // err := f.SetColWidth("Sheet1", "A", "H", 20) // -func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) error { - min, err := ColumnNameToNumber(startcol) +func (f *File) SetColWidth(sheet, startCol, endCol string, width float64) error { + min, err := ColumnNameToNumber(startCol) if err != nil { return err } - max, err := ColumnNameToNumber(endcol) + max, err := ColumnNameToNumber(endCol) if err != nil { return err } @@ -502,7 +499,7 @@ func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) error // flatCols provides a method for the column's operation functions to flatten // and check the worksheet columns. func flatCols(col xlsxCol, cols []xlsxCol, replacer func(fc, c xlsxCol) xlsxCol) []xlsxCol { - fc := []xlsxCol{} + var fc []xlsxCol for i := col.Min; i <= col.Max; i++ { c := deepcopy.Copy(col).(xlsxCol) c.Min, c.Max = i, i @@ -547,7 +544,7 @@ func flatCols(col xlsxCol, cols []xlsxCol, replacer func(fc, c xlsxCol) xlsxCol) // | | | (x2,y2)| // +-----+------------+------------+ // -// Example of an object that covers some of the area from cell A1 to B2. +// Example of an object that covers some area from cell A1 to B2. // // Based on the width and height of the object we need to calculate 8 vars: // diff --git a/comment.go b/comment.go index 6cebfee..a7c1415 100644 --- a/comment.go +++ b/comment.go @@ -47,7 +47,7 @@ func (f *File) GetComments() (comments map[string][]Comment) { target = "xl" + strings.TrimPrefix(target, "..") } if d := f.commentsReader(strings.TrimPrefix(target, "/")); d != nil { - sheetComments := []Comment{} + var sheetComments []Comment for _, comment := range d.CommentList.Comment { sheetComment := Comment{} if comment.AuthorID < len(d.Authors.Author) { diff --git a/crypt.go b/crypt.go index c579a10..8a783a9 100644 --- a/crypt.go +++ b/crypt.go @@ -629,7 +629,7 @@ func genISOPasswdHash(passwd, hashAlgorithm, salt string, spinCount int) (hashVa err = ErrPasswordLengthInvalid return } - hash, ok := map[string]string{ + algorithmName, ok := map[string]string{ "MD4": "md4", "MD5": "md5", "SHA-1": "sha1", @@ -653,11 +653,11 @@ func genISOPasswdHash(passwd, hashAlgorithm, salt string, spinCount int) (hashVa passwordBuffer, _ := encoder.Bytes([]byte(passwd)) b.Write(passwordBuffer) // Generate the initial hash. - key := hashing(hash, b.Bytes()) + key := hashing(algorithmName, b.Bytes()) // Now regenerate until spin count. for i := 0; i < spinCount; i++ { iterator := createUInt32LEBuffer(i, 4) - key = hashing(hash, key, iterator) + key = hashing(algorithmName, key, iterator) } hashValue, saltValue = base64.StdEncoding.EncodeToString(key), base64.StdEncoding.EncodeToString(s) return diff --git a/crypt_test.go b/crypt_test.go index 45e8815..80f6cc4 100644 --- a/crypt_test.go +++ b/crypt_test.go @@ -34,7 +34,7 @@ func TestEncryptionMechanism(t *testing.T) { } func TestHashing(t *testing.T) { - assert.Equal(t, hashing("unsupportedHashAlgorithm", []byte{}), []uint8([]byte(nil))) + assert.Equal(t, hashing("unsupportedHashAlgorithm", []byte{}), []byte(nil)) } func TestGenISOPasswdHash(t *testing.T) { diff --git a/datavalidation.go b/datavalidation.go index d0e927b..4df2c50 100644 --- a/datavalidation.go +++ b/datavalidation.go @@ -129,27 +129,27 @@ func (dd *DataValidation) SetRange(f1, f2 interface{}, t DataValidationType, o D var formula1, formula2 string switch v := f1.(type) { case int: - formula1 = fmt.Sprintf("%d", int(v)) + formula1 = fmt.Sprintf("%d", v) case float64: - if math.Abs(float64(v)) > math.MaxFloat32 { + if math.Abs(v) > math.MaxFloat32 { return ErrDataValidationRange } - formula1 = fmt.Sprintf("%.17g", float64(v)) + formula1 = fmt.Sprintf("%.17g", v) case string: - formula1 = fmt.Sprintf("%s", string(v)) + formula1 = fmt.Sprintf("%s", v) default: return ErrParameterInvalid } switch v := f2.(type) { case int: - formula2 = fmt.Sprintf("%d", int(v)) + formula2 = fmt.Sprintf("%d", v) case float64: - if math.Abs(float64(v)) > math.MaxFloat32 { + if math.Abs(v) > math.MaxFloat32 { return ErrDataValidationRange } - formula2 = fmt.Sprintf("%.17g", float64(v)) + formula2 = fmt.Sprintf("%.17g", v) case string: - formula2 = fmt.Sprintf("%s", string(v)) + formula2 = fmt.Sprintf("%s", v) default: return ErrParameterInvalid } @@ -277,7 +277,7 @@ func (f *File) DeleteDataValidation(sheet, sqref string) error { } dv := ws.DataValidations for i := 0; i < len(dv.DataValidation); i++ { - applySqref := []string{} + var applySqref []string colCells, err := f.flatSqref(dv.DataValidation[i].Sqref) if err != nil { return err @@ -314,7 +314,8 @@ func (f *File) squashSqref(cells [][]int) []string { } else if len(cells) == 0 { return []string{} } - l, r, res := 0, 0, []string{} + var res []string + l, r := 0, 0 for i := 1; i < len(cells); i++ { if cells[i][0] == cells[r][0] && cells[i][1]-cells[r][1] > 1 { curr, _ := f.coordinatesToAreaRef(append(cells[l], cells[r]...)) diff --git a/drawing.go b/drawing.go index e3e7fa8..1daa912 100644 --- a/drawing.go +++ b/drawing.go @@ -740,7 +740,7 @@ func (f *File) drawChartShape(formatSet *formatChart) *attrValString { // drawChartSeries provides a function to draw the c:ser element by given // format sets. func (f *File) drawChartSeries(formatSet *formatChart) *[]cSer { - ser := []cSer{} + var ser []cSer for k := range formatSet.Series { ser = append(ser, cSer{ IDx: &attrValInt{Val: intPtr(k + formatSet.order)}, diff --git a/errors.go b/errors.go index 1047704..c9d18cb 100644 --- a/errors.go +++ b/errors.go @@ -138,9 +138,9 @@ var ( // ErrDefinedNameScope defined the error message on not found defined name // in the given scope. ErrDefinedNameScope = errors.New("no defined name on the scope") - // ErrDefinedNameduplicate defined the error message on the same name + // ErrDefinedNameDuplicate defined the error message on the same name // already exists on the scope. - ErrDefinedNameduplicate = errors.New("the same name already exists on the scope") + ErrDefinedNameDuplicate = errors.New("the same name already exists on the scope") // ErrCustomNumFmt defined the error message on receive the empty custom number format. ErrCustomNumFmt = errors.New("custom number format can not be empty") // ErrFontLength defined the error message on the length of the font diff --git a/excelize.go b/excelize.go index 0aebfc4..9fe3d88 100644 --- a/excelize.go +++ b/excelize.go @@ -102,13 +102,16 @@ func OpenFile(filename string, opt ...Options) (*File, error) { if err != nil { return nil, err } - defer file.Close() f, err := OpenReader(file, opt...) if err != nil { - return nil, err + closeErr := file.Close() + if closeErr == nil { + return f, err + } + return f, closeErr } f.Path = filename - return f, nil + return f, file.Close() } // newFile is object builder diff --git a/excelize_test.go b/excelize_test.go index 7d38304..dc5dfcc 100644 --- a/excelize_test.go +++ b/excelize_test.go @@ -40,11 +40,11 @@ func TestOpenFile(t *testing.T) { } assert.NoError(t, f.UpdateLinkedValue()) - assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(float64(100.1588), 'f', -1, 32))) - assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(float64(-100.1588), 'f', -1, 64))) + assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(100.1588, 'f', -1, 32))) + assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(-100.1588, 'f', -1, 64))) // Test set cell value with illegal row number. - assert.EqualError(t, f.SetCellDefault("Sheet2", "A", strconv.FormatFloat(float64(-100.1588), 'f', -1, 64)), + assert.EqualError(t, f.SetCellDefault("Sheet2", "A", strconv.FormatFloat(-100.1588, 'f', -1, 64)), newCellNameToCoordinatesError("A", newInvalidCellNameError("A")).Error()) assert.NoError(t, f.SetCellInt("Sheet2", "A1", 100)) @@ -109,7 +109,7 @@ func TestOpenFile(t *testing.T) { assert.NoError(t, f.SetCellValue("Sheet2", "F5", int32(1<<32/2-1))) assert.NoError(t, f.SetCellValue("Sheet2", "F6", int64(1<<32/2-1))) assert.NoError(t, f.SetCellValue("Sheet2", "F7", float32(42.65418))) - assert.NoError(t, f.SetCellValue("Sheet2", "F8", float64(-42.65418))) + assert.NoError(t, f.SetCellValue("Sheet2", "F8", -42.65418)) assert.NoError(t, f.SetCellValue("Sheet2", "F9", float32(42))) assert.NoError(t, f.SetCellValue("Sheet2", "F10", float64(42))) assert.NoError(t, f.SetCellValue("Sheet2", "F11", uint(1<<32-1))) @@ -1157,9 +1157,9 @@ func TestHSL(t *testing.T) { assert.Equal(t, 0.0, hueToRGB(0, 0, 2.0/4)) t.Log(RGBToHSL(255, 255, 0)) h, s, l := RGBToHSL(0, 255, 255) - assert.Equal(t, float64(0.5), h) - assert.Equal(t, float64(1), s) - assert.Equal(t, float64(0.5), l) + assert.Equal(t, 0.5, h) + assert.Equal(t, 1.0, s) + assert.Equal(t, 0.5, l) t.Log(RGBToHSL(250, 100, 50)) t.Log(RGBToHSL(50, 100, 250)) t.Log(RGBToHSL(250, 50, 100)) diff --git a/lib.go b/lib.go index 439e50a..4205e08 100644 --- a/lib.go +++ b/lib.go @@ -80,10 +80,13 @@ func (f *File) unzipToTemp(zipFile *zip.File) (string, error) { if err != nil { return tmp.Name(), err } - _, err = io.Copy(tmp, rc) - rc.Close() - tmp.Close() - return tmp.Name(), err + if _, err = io.Copy(tmp, rc); err != nil { + return tmp.Name(), err + } + if err = rc.Close(); err != nil { + return tmp.Name(), err + } + return tmp.Name(), tmp.Close() } // readXML provides a function to read XML content as bytes. @@ -109,7 +112,7 @@ func (f *File) readBytes(name string) []byte { } content, _ = ioutil.ReadAll(file) f.Pkg.Store(name, content) - file.Close() + _ = file.Close() return content } @@ -437,9 +440,10 @@ func (avb attrValBool) MarshalXML(e *xml.Encoder, start xml.StartElement) error } } start.Attr = []xml.Attr{attr} - e.EncodeToken(start) - e.EncodeToken(start.End()) - return nil + if err := e.EncodeToken(start); err != nil { + return err + } + return e.EncodeToken(start.End()) } // UnmarshalXML convert the literal values true, false, 1, 0 of the XML @@ -558,7 +562,7 @@ func genSheetPasswd(plaintext string) string { charPos++ rotatedBits := value >> 15 // rotated bits beyond bit 15 value &= 0x7fff // first 15 bits - password ^= (value | rotatedBits) + password ^= value | rotatedBits } password ^= int64(len(plaintext)) password ^= 0xCE4B @@ -793,8 +797,8 @@ type Stack struct { // NewStack create a new stack. func NewStack() *Stack { - list := list.New() - return &Stack{list} + l := list.New() + return &Stack{l} } // Push a value onto the top of the stack. diff --git a/merge_test.go b/merge_test.go index a28aeff..597d4b5 100644 --- a/merge_test.go +++ b/merge_test.go @@ -23,7 +23,7 @@ func TestMergeCell(t *testing.T) { assert.NoError(t, f.MergeCell("Sheet1", "G10", "K12")) assert.NoError(t, f.SetCellValue("Sheet1", "G11", "set value in merged cell")) assert.NoError(t, f.SetCellInt("Sheet1", "H11", 100)) - assert.NoError(t, f.SetCellValue("Sheet1", "I11", float64(0.5))) + assert.NoError(t, f.SetCellValue("Sheet1", "I11", 0.5)) assert.NoError(t, f.SetCellHyperLink("Sheet1", "J11", "https://github.com/xuri/excelize", "External")) assert.NoError(t, f.SetCellFormula("Sheet1", "G12", "SUM(Sheet1!B19,Sheet1!C19)")) value, err := f.GetCellValue("Sheet1", "H11") diff --git a/numfmt.go b/numfmt.go index 3b20e02..685005f 100644 --- a/numfmt.go +++ b/numfmt.go @@ -456,7 +456,7 @@ func localMonthsNameIrish(t time.Time, abbr int) string { } } if abbr == 4 { - return string([]rune(monthNamesIrish[int(t.Month())-1])) + return monthNamesIrish[int(t.Month())-1] } return string([]rune(monthNamesIrish[int(t.Month())-1])[:1]) } @@ -536,7 +536,7 @@ func localMonthsNameRussian(t time.Time, abbr int) string { return string([]rune(month)[:3]) + "." } if abbr == 4 { - return string([]rune(monthNamesRussian[int(t.Month())-1])) + return monthNamesRussian[int(t.Month())-1] } return string([]rune(monthNamesRussian[int(t.Month())-1])[:1]) } @@ -559,7 +559,7 @@ func localMonthsNameThai(t time.Time, abbr int) string { return string(r[:1]) + "." + string(r[len(r)-2:len(r)-1]) + "." } if abbr == 4 { - return string([]rune(monthNamesThai[int(t.Month())-1])) + return monthNamesThai[int(t.Month())-1] } return string([]rune(monthNamesThai[int(t.Month())-1])[:1]) } @@ -575,7 +575,7 @@ func localMonthsNameTibetan(t time.Time, abbr int) string { } return "\u0f5f" } - return string(monthNamesTibetan[int(t.Month())-1]) + return monthNamesTibetan[int(t.Month())-1] } // localMonthsNameTurkish returns the Turkish name of the month. @@ -661,7 +661,7 @@ func localMonthsNameXhosa(t time.Time, abbr int) string { // localMonthsNameYi returns the Yi name of the month. func localMonthsNameYi(t time.Time, abbr int) string { if abbr == 3 || abbr == 4 { - return string([]rune(monthNamesYi[int(t.Month())-1])) + "\ua1aa" + return string(monthNamesYi[int(t.Month())-1]) + "\ua1aa" } return string([]rune(monthNamesYi[int(t.Month())-1])[:1]) } diff --git a/picture.go b/picture.go index 180983d..515f15f 100644 --- a/picture.go +++ b/picture.go @@ -76,7 +76,7 @@ func parseFormatPictureSet(formatSet string) (*formatPicture, error) { // } // } // -// The optional parameter "autofit" specifies if make image size auto fits the +// The optional parameter "autofit" specifies if you make image size auto-fits the // cell, the default value of that is 'false'. // // The optional parameter "hyperlink" specifies the hyperlink of the image. @@ -86,7 +86,7 @@ func parseFormatPictureSet(formatSet string) (*formatPicture, error) { // cells in this workbook. When the "hyperlink_type" is "Location", // coordinates need to start with "#". // -// The optional parameter "positioning" defines two types of the position of a +// The optional parameter "positioning" defines two types of the position of an // image in an Excel spreadsheet, "oneCell" (Move but don't size with // cells) or "absolute" (Don't move or size with cells). If you don't set this // parameter, the default positioning is move and size with cells. diff --git a/pivotTable.go b/pivotTable.go index 5810968..437d22f 100644 --- a/pivotTable.go +++ b/pivotTable.go @@ -132,7 +132,7 @@ type PivotTableField struct { // func (f *File) AddPivotTable(opt *PivotTableOption) error { // parameter validation - dataSheet, pivotTableSheetPath, err := f.parseFormatPivotTableSet(opt) + _, pivotTableSheetPath, err := f.parseFormatPivotTableSet(opt) if err != nil { return err } @@ -143,7 +143,7 @@ func (f *File) AddPivotTable(opt *PivotTableOption) error { sheetRelationshipsPivotTableXML := "../pivotTables/pivotTable" + strconv.Itoa(pivotTableID) + ".xml" pivotTableXML := strings.Replace(sheetRelationshipsPivotTableXML, "..", "xl", -1) pivotCacheXML := "xl/pivotCache/pivotCacheDefinition" + strconv.Itoa(pivotCacheID) + ".xml" - err = f.addPivotCache(pivotCacheID, pivotCacheXML, opt, dataSheet) + err = f.addPivotCache(pivotCacheXML, opt) if err != nil { return err } @@ -230,7 +230,7 @@ func (f *File) adjustRange(rangeStr string) (string, []int, error) { // getPivotFieldsOrder provides a function to get order list of pivot table // fields. func (f *File) getPivotFieldsOrder(opt *PivotTableOption) ([]string, error) { - order := []string{} + var order []string dataRange := f.getDefinedNameRefTo(opt.DataRange, opt.pivotTableSheetName) if dataRange == "" { dataRange = opt.DataRange @@ -251,7 +251,7 @@ func (f *File) getPivotFieldsOrder(opt *PivotTableOption) ([]string, error) { } // addPivotCache provides a function to create a pivot cache by given properties. -func (f *File) addPivotCache(pivotCacheID int, pivotCacheXML string, opt *PivotTableOption, ws *xlsxWorksheet) error { +func (f *File) addPivotCache(pivotCacheXML string, opt *PivotTableOption) error { // validate data range definedNameRef := true dataRange := f.getDefinedNameRefTo(opt.DataRange, opt.pivotTableSheetName) @@ -626,7 +626,7 @@ func (f *File) countPivotCache() int { // getPivotFieldsIndex convert the column of the first row in the data region // to a sequential index by given fields and pivot option. func (f *File) getPivotFieldsIndex(fields []PivotTableField, opt *PivotTableOption) ([]int, error) { - pivotFieldsIndex := []int{} + var pivotFieldsIndex []int orders, err := f.getPivotFieldsOrder(opt) if err != nil { return pivotFieldsIndex, err diff --git a/pivotTable_test.go b/pivotTable_test.go index d7a8eb1..2f95ed4 100644 --- a/pivotTable_test.go +++ b/pivotTable_test.go @@ -235,15 +235,15 @@ func TestAddPivotTable(t *testing.T) { _, err = f.getPivotFieldsOrder(&PivotTableOption{}) assert.EqualError(t, err, `parameter 'DataRange' parsing error: parameter is required`) // Test add pivot cache with empty data range - assert.EqualError(t, f.addPivotCache(0, "", &PivotTableOption{}, nil), "parameter 'DataRange' parsing error: parameter is required") + assert.EqualError(t, f.addPivotCache("", &PivotTableOption{}), "parameter 'DataRange' parsing error: parameter is required") // Test add pivot cache with invalid data range - assert.EqualError(t, f.addPivotCache(0, "", &PivotTableOption{ + assert.EqualError(t, f.addPivotCache("", &PivotTableOption{ DataRange: "$A$1:$E$31", PivotTableRange: "Sheet1!$U$34:$O$2", Rows: []PivotTableField{{Data: "Month", DefaultSubtotal: true}, {Data: "Year"}}, Columns: []PivotTableField{{Data: "Type", DefaultSubtotal: true}}, Data: []PivotTableField{{Data: "Sales"}}, - }, nil), "parameter 'DataRange' parsing error: parameter is invalid") + }), "parameter 'DataRange' parsing error: parameter is invalid") // Test add pivot table with empty options assert.EqualError(t, f.addPivotTable(0, 0, "", &PivotTableOption{}), "parameter 'PivotTableRange' parsing error: parameter is required") // Test add pivot table with invalid data range diff --git a/rows.go b/rows.go index ae7e01e..e0918bc 100644 --- a/rows.go +++ b/rows.go @@ -179,7 +179,7 @@ type ErrSheetNotExist struct { } func (err ErrSheetNotExist) Error() string { - return fmt.Sprintf("sheet %s is not exist", string(err.SheetName)) + return fmt.Sprintf("sheet %s is not exist", err.SheetName) } // rowXMLIterator defined runtime use field for the worksheet row SAX parser. diff --git a/sheet.go b/sheet.go index 78fcaf2..3986cd8 100644 --- a/sheet.go +++ b/sheet.go @@ -36,7 +36,7 @@ import ( // NewSheet provides the function to create a new sheet by given a worksheet // name and returns the index of the sheets in the workbook // (spreadsheet) after it appended. Note that the worksheet names are not -// case sensitive, when creating a new spreadsheet file, the default +// case-sensitive, when creating a new spreadsheet file, the default // worksheet named `Sheet1` will be created. func (f *File) NewSheet(name string) int { // Check if the worksheet already exists @@ -111,7 +111,7 @@ func (f *File) mergeExpandedCols(ws *xlsxWorksheet) { sort.Slice(ws.Cols.Col, func(i, j int) bool { return ws.Cols.Col[i].Min < ws.Cols.Col[j].Min }) - columns := []xlsxCol{} + var columns []xlsxCol for i, n := 0, len(ws.Cols.Col); i < n; { left := i for i++; i < n && reflect.DeepEqual( @@ -219,10 +219,10 @@ func (f *File) setSheet(index int, name string) { SheetView: []xlsxSheetView{{WorkbookViewID: 0}}, }, } - path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml" - f.sheetMap[trimSheetName(name)] = path - f.Sheet.Store(path, &ws) - f.xmlAttr[path] = []xml.Attr{NameSpaceSpreadSheet} + sheetXMLPath := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml" + f.sheetMap[trimSheetName(name)] = sheetXMLPath + f.Sheet.Store(sheetXMLPath, &ws) + f.xmlAttr[sheetXMLPath] = []xml.Attr{NameSpaceSpreadSheet} } // relsWriter provides a function to save relationships after @@ -384,7 +384,7 @@ func (f *File) getSheetID(name string) int { } // GetSheetIndex provides a function to get a sheet index of the workbook by -// the given sheet name, the sheet names are not case sensitive. If the given +// the given sheet name, the sheet names are not case-sensitive. If the given // sheet name is invalid or sheet doesn't exist, it will return an integer // type value -1. func (f *File) GetSheetIndex(name string) int { @@ -442,12 +442,12 @@ func (f *File) getSheetMap() map[string]string { for _, v := range f.workbookReader().Sheets.Sheet { for _, rel := range f.relsReader(f.getWorkbookRelsPath()).Relationships { if rel.ID == v.ID { - path := f.getWorksheetPath(rel.Target) - if _, ok := f.Pkg.Load(path); ok { - maps[v.Name] = path + sheetXMLPath := f.getWorksheetPath(rel.Target) + if _, ok := f.Pkg.Load(sheetXMLPath); ok { + maps[v.Name] = sheetXMLPath } - if _, ok := f.tempFiles.Load(path); ok { - maps[v.Name] = path + if _, ok := f.tempFiles.Load(sheetXMLPath); ok { + maps[v.Name] = sheetXMLPath } } } @@ -478,8 +478,8 @@ func (f *File) SetSheetBackground(sheet, picture string) error { } // DeleteSheet provides a function to delete worksheet in a workbook by given -// worksheet name, the sheet names are not case sensitive.the sheet names are -// not case sensitive. Use this method with caution, which will affect +// worksheet name, the sheet names are not case-sensitive. The sheet names are +// not case-sensitive. Use this method with caution, which will affect // changes in references such as formulas, charts, and so on. If there is any // referenced value of the deleted worksheet, it will cause a file error when // you open it. This function will be invalid when only the one worksheet is @@ -601,14 +601,14 @@ func (f *File) copySheet(from, to int) error { } worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet) toSheetID := strconv.Itoa(f.getSheetID(f.GetSheetName(to))) - path := "xl/worksheets/sheet" + toSheetID + ".xml" + sheetXMLPath := "xl/worksheets/sheet" + toSheetID + ".xml" if len(worksheet.SheetViews.SheetView) > 0 { worksheet.SheetViews.SheetView[0].TabSelected = false } worksheet.Drawing = nil worksheet.TableParts = nil worksheet.PageSetUp = nil - f.Sheet.Store(path, worksheet) + f.Sheet.Store(sheetXMLPath, worksheet) toRels := "xl/worksheets/_rels/sheet" + toSheetID + ".xml.rels" fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(f.getSheetID(fromSheet)) + ".xml.rels" if rels, ok := f.Pkg.Load(fromRels); ok && rels != nil { @@ -616,7 +616,7 @@ func (f *File) copySheet(from, to int) error { } fromSheetXMLPath := f.sheetMap[trimSheetName(fromSheet)] fromSheetAttr := f.xmlAttr[fromSheetXMLPath] - f.xmlAttr[path] = fromSheetAttr + f.xmlAttr[sheetXMLPath] = fromSheetAttr return err } @@ -779,7 +779,7 @@ func (f *File) SetPanes(sheet, panes string) error { ws.SheetViews.SheetView[len(ws.SheetViews.SheetView)-1].Pane = nil } } - s := []*xlsxSelection{} + var s []*xlsxSelection for _, p := range fs.Panes { s = append(s, &xlsxSelection{ ActiveCell: p.ActiveCell, @@ -1207,7 +1207,7 @@ type ( // FitToWidth specified the number of horizontal pages to fit on. FitToWidth int // PageLayoutScale defines the print scaling. This attribute is restricted - // to values ranging from 10 (10%) to 400 (400%). This setting is + // to value ranging from 10 (10%) to 400 (400%). This setting is // overridden when fitToWidth and/or fitToHeight are in use. PageLayoutScale uint ) @@ -1534,7 +1534,7 @@ func (f *File) SetDefinedName(definedName *DefinedName) error { scope = f.GetSheetName(*dn.LocalSheetID) } if scope == definedName.Scope && dn.Name == definedName.Name { - return ErrDefinedNameduplicate + return ErrDefinedNameDuplicate } } wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName, d) @@ -1616,7 +1616,7 @@ func (f *File) GroupSheets(sheets []string) error { return ErrGroupSheets } // check worksheet exists - wss := []*xlsxWorksheet{} + var wss []*xlsxWorksheet for _, sheet := range sheets { worksheet, err := f.workSheetReader(sheet) if err != nil { diff --git a/sheet_test.go b/sheet_test.go index 429f617..db36417 100644 --- a/sheet_test.go +++ b/sheet_test.go @@ -276,7 +276,7 @@ func TestDefinedName(t *testing.T) { Name: "Amount", RefersTo: "Sheet1!$A$2:$D$5", Comment: "defined name comment", - }), ErrDefinedNameduplicate.Error()) + }), ErrDefinedNameDuplicate.Error()) assert.EqualError(t, f.DeleteDefinedName(&DefinedName{ Name: "No Exist Defined Name", }), ErrDefinedNameScope.Error()) diff --git a/sheetview.go b/sheetview.go index 8650b32..bf8f023 100644 --- a/sheetview.go +++ b/sheetview.go @@ -135,7 +135,7 @@ func (o *View) getSheetViewOption(view *xlsxSheetView) { *o = View(view.View) return } - *o = View("normal") + *o = "normal" } func (o TopLeftCell) setSheetViewOption(view *xlsxSheetView) { @@ -143,7 +143,7 @@ func (o TopLeftCell) setSheetViewOption(view *xlsxSheetView) { } func (o *TopLeftCell) getSheetViewOption(view *xlsxSheetView) { - *o = TopLeftCell(string(view.TopLeftCell)) + *o = TopLeftCell(view.TopLeftCell) } func (o ZoomScale) setSheetViewOption(view *xlsxSheetView) { diff --git a/sparkline.go b/sparkline.go index 5a480b9..880724a 100644 --- a/sparkline.go +++ b/sparkline.go @@ -362,7 +362,7 @@ func (f *File) addSparklineGroupByStyle(ID int) *xlsxX14SparklineGroup { // given formatting options. Sparklines are small charts that fit in a single // cell and are used to show trends in data. Sparklines are a feature of Excel // 2010 and later only. You can write them to an XLSX file that can be read by -// Excel 2007 but they won't be displayed. For example, add a grouped +// Excel 2007, but they won't be displayed. For example, add a grouped // sparkline. Changes are applied to all three: // // err := f.AddSparkline("Sheet1", &excelize.SparklineOption{ diff --git a/stream.go b/stream.go index a9ec2cf..c2eda68 100644 --- a/stream.go +++ b/stream.go @@ -136,7 +136,7 @@ func (f *File) NewStreamWriter(sheet string) (*StreamWriter, error) { // Note that the table must be at least two lines including the header. The // header cells must contain strings and must be unique. // -// Currently only one table is allowed for a StreamWriter. AddTable must be +// Currently, only one table is allowed for a StreamWriter. AddTable must be // called after the rows are written but before Flush. // // See File.AddTable for details on the table format. diff --git a/stream_test.go b/stream_test.go index 7a93380..3df898a 100644 --- a/stream_test.go +++ b/stream_test.go @@ -223,7 +223,7 @@ func TestSetCellValFunc(t *testing.T) { assert.NoError(t, sw.setCellValFunc(c, uint32(4294967295))) assert.NoError(t, sw.setCellValFunc(c, uint64(18446744073709551615))) assert.NoError(t, sw.setCellValFunc(c, float32(100.1588))) - assert.NoError(t, sw.setCellValFunc(c, float64(100.1588))) + assert.NoError(t, sw.setCellValFunc(c, 100.1588)) assert.NoError(t, sw.setCellValFunc(c, " Hello")) assert.NoError(t, sw.setCellValFunc(c, []byte(" Hello"))) assert.NoError(t, sw.setCellValFunc(c, time.Now().UTC())) diff --git a/styles.go b/styles.go index 6d6d7bb..c04ca3b 100644 --- a/styles.go +++ b/styles.go @@ -2465,7 +2465,7 @@ func (f *File) GetCellStyle(sheet, axis string) (int, error) { if err != nil { return 0, err } - cellData, col, row, err := f.prepareCell(ws, sheet, axis) + cellData, col, row, err := f.prepareCell(ws, axis) if err != nil { return 0, err } @@ -2851,7 +2851,7 @@ func (f *File) SetConditionalFormat(sheet, area, formatSet string) error { if err != nil { return err } - cfRule := []*xlsxCfRule{} + var cfRule []*xlsxCfRule for p, v := range format { var vt, ct string var ok bool @@ -3052,7 +3052,7 @@ func ThemeColor(baseColor string, tint float64) string { h, s, l = RGBToHSL(uint8(r), uint8(g), uint8(b)) } if tint < 0 { - l *= (1 + tint) + l *= 1 + tint } else { l = l*(1-tint) + (1 - (1 - tint)) } diff --git a/styles_test.go b/styles_test.go index de3444f..a71041d 100644 --- a/styles_test.go +++ b/styles_test.go @@ -212,10 +212,10 @@ func TestNewStyle(t *testing.T) { assert.EqualError(t, err, ErrFontSize.Error()) // new numeric custom style - fmt := "####;####" + numFmt := "####;####" f.Styles.NumFmts = nil styleID, err = f.NewStyle(&Style{ - CustomNumFmt: &fmt, + CustomNumFmt: &numFmt, }) assert.NoError(t, err) assert.Equal(t, 2, styleID) diff --git a/table.go b/table.go index 1fcb448..0311a8e 100644 --- a/table.go +++ b/table.go @@ -383,7 +383,7 @@ func (f *File) writeAutoFilter(filter *xlsxAutoFilter, exp []int, tokens []strin filter.FilterColumn[0].Filters = &xlsxFilters{Filter: filters} } else if len(exp) == 3 && exp[0] == 2 && exp[1] == 1 && exp[2] == 2 { // Double equality with "or" operator. - filters := []*xlsxFilter{} + var filters []*xlsxFilter for _, v := range tokens { filters = append(filters, &xlsxFilter{Val: v}) } @@ -419,7 +419,7 @@ func (f *File) writeCustomFilter(filter *xlsxAutoFilter, operator int, val strin if filter.FilterColumn[0].CustomFilters != nil { filter.FilterColumn[0].CustomFilters.CustomFilter = append(filter.FilterColumn[0].CustomFilters.CustomFilter, &customFilter) } else { - customFilters := []*xlsxCustomFilter{} + var customFilters []*xlsxCustomFilter customFilters = append(customFilters, &customFilter) filter.FilterColumn[0].CustomFilters = &xlsxCustomFilters{CustomFilter: customFilters} } @@ -435,8 +435,8 @@ func (f *File) writeCustomFilter(filter *xlsxAutoFilter, operator int, val strin // ('x', '>', 2000, 'and', 'x', '<', 5000) -> exp1 and exp2 // func (f *File) parseFilterExpression(expression string, tokens []string) ([]int, []string, error) { - expressions := []int{} - t := []string{} + var expressions []int + var t []string if len(tokens) == 7 { // The number of tokens will be either 3 (for 1 expression) or 7 (for 2 // expressions). diff --git a/templates.go b/templates.go index 9468341..1e46b56 100644 --- a/templates.go +++ b/templates.go @@ -14,12 +14,6 @@ package excelize -import "encoding/xml" - -// XMLHeaderByte define an XML declaration can also contain a standalone -// declaration. -var XMLHeaderByte = []byte(xml.Header) - const ( defaultXMLPathContentTypes = "[Content_Types].xml" defaultXMLPathDocPropsApp = "docProps/app.xml" diff --git a/xmlCalcChain.go b/xmlCalcChain.go index 401bf2c..f578033 100644 --- a/xmlCalcChain.go +++ b/xmlCalcChain.go @@ -66,13 +66,13 @@ type xlsxCalcChain struct { // | same dependency level. Child chains are series of // | calculations that can be independently farmed out to // | other threads or processors.The possible values for -// | this attribute are defined by the W3C XML Schema +// | this attribute is defined by the W3C XML Schema // | boolean datatype. // | // t (New Thread) | A Boolean flag indicating whether the cell's formula // | starts a new thread. True if the cell's formula starts // | a new thread, false otherwise.The possible values for -// | this attribute are defined by the W3C XML Schema +// | this attribute is defined by the W3C XML Schema // | boolean datatype. // type xlsxCalcChainC struct { diff --git a/xmlContentTypes.go b/xmlContentTypes.go index 5920f1f..4b3cd64 100644 --- a/xmlContentTypes.go +++ b/xmlContentTypes.go @@ -16,7 +16,7 @@ import ( "sync" ) -// xlsxTypes directly maps the types element of content types for relationship +// xlsxTypes directly maps the types' element of content types for relationship // parts, it takes a Multipurpose Internet Mail Extension (MIME) media type as a // value. type xlsxTypes struct { diff --git a/xmlStyles.go b/xmlStyles.go index c70ab60..71fe9a6 100644 --- a/xmlStyles.go +++ b/xmlStyles.go @@ -197,7 +197,7 @@ type xlsxCellStyle struct { // contains the master formatting records (xf's) which define the formatting for // all named cell styles in this workbook. Master formatting records reference // individual elements of formatting (e.g., number format, font definitions, -// cell fills, etc) by specifying a zero-based index into those collections. +// cell fills, etc.) by specifying a zero-based index into those collections. // Master formatting records also specify whether to apply or ignore particular // aspects of formatting. type xlsxCellStyleXfs struct { diff --git a/xmlTable.go b/xmlTable.go index 4afc26d..5a56a83 100644 --- a/xmlTable.go +++ b/xmlTable.go @@ -14,7 +14,7 @@ package excelize import "encoding/xml" // xlsxTable directly maps the table element. A table helps organize and provide -// structure to lists of information in a worksheet. Tables have clearly labeled +// structure to list of information in a worksheet. Tables have clearly labeled // columns, rows, and data regions. Tables make it easier for users to sort, // analyze, format, manage, add, and delete information. This element is the // root element for a table that is not a single cell XML table.