Showing 1 changed files with 31 additions and 1 deletions
+31 -1
csv2xlsx.go
... ...
@@ -6,6 +6,7 @@ import (
6 6
 	"flag"
7 7
 	"fmt"
8 8
 	"io"
9
+	"math"
9 10
 	"os"
10 11
 	"path/filepath"
11 12
 	"strconv"
... ...
@@ -43,6 +44,35 @@ var (
43 44
 	tmpStr              string
44 45
 )
45 46
 
47
+// ParseFloat ist an advanced ParseFloat for golang, support scientific notation, comma separated number
48
+// from yyscamper at https://gist.github.com/yyscamper/5657c360fadd6701580f3c0bcca9f63a
49
+func ParseFloat(str string) (float64, error) {
50
+	val, err := strconv.ParseFloat(str, 64)
51
+	if err == nil {
52
+		return val, nil
53
+	}
54
+	//Some number may be seperated by comma, for example, 23,120,123, so remove the comma firstly
55
+	str = strings.Replace(str, ",", "", -1)
56
+	//Some number is specifed in scientific notation
57
+	pos := strings.IndexAny(str, "eE")
58
+	if pos < 0 {
59
+		return strconv.ParseFloat(str, 64)
60
+	}
61
+	var baseVal float64
62
+	var expVal int64
63
+	baseStr := str[0:pos]
64
+	baseVal, err = strconv.ParseFloat(baseStr, 64)
65
+	if err != nil {
66
+		return 0, err
67
+	}
68
+	expStr := str[(pos + 1):]
69
+	expVal, err = strconv.ParseInt(expStr, 10, 64)
70
+	if err != nil {
71
+		return 0, err
72
+	}
73
+	return baseVal * math.Pow10(int(expVal)), nil
74
+}
75
+
46 76
 // parseCommaGroup parses a single comma group (x or x-y),
47 77
 // optionally followed by :datatype (used only for columns right now)
48 78
 // It returns a map with row or column index as key and the datatype as value
... ...
@@ -307,7 +337,7 @@ func writeCellContents(cell *xlsx.Cell, colString, colType string, rownum, colnu
307 337
 	case "text":
308 338
 		cell.SetString(colString)
309 339
 	case "number", "currency":
310
-		floatVal, err := strconv.ParseFloat(colString, 64)
340
+		floatVal, err := ParseFloat(colString)
311 341
 		if err != nil {
312 342
 			fmt.Println(fmt.Sprintf("Cell (%d,%d) is not a valid number, value: %s", rownum, colnum, colString))
313 343
 			success = false