|
1 | 1 | package table
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
| 5 | + "encoding/csv" |
4 | 6 | "errors"
|
5 | 7 | "fmt"
|
| 8 | + "strings" |
6 | 9 |
|
7 | 10 | "github.com/grokify/simplego/math/mathutil"
|
8 | 11 | )
|
9 | 12 |
|
10 |
| -// FormatStraightToTabular takes a "straight table" wheere the columnn names |
| 13 | +// Pivot takes a "straight table" where the columnn names |
11 | 14 | // and values are in a single column and lays it out as a standard tabular data.
|
12 |
| -func FormatStraightToTabular(tbl Table, colCount uint) (Table, error) { |
| 15 | +func (tbl *Table) Pivot(colCount uint) (Table, error) { |
13 | 16 | newTbl := NewTable(tbl.Name)
|
14 | 17 | if len(tbl.Columns) != 0 {
|
15 |
| - return newTbl, fmt.Errorf("Has Defined Columns Count [%d]", len(tbl.Columns)) |
| 18 | + return newTbl, fmt.Errorf("has defined columns count [%d]", len(tbl.Columns)) |
16 | 19 | }
|
17 | 20 | isWellFormed, colCountActual := tbl.IsWellFormed()
|
18 | 21 | if !isWellFormed {
|
@@ -41,3 +44,29 @@ func FormatStraightToTabular(tbl Table, colCount uint) (Table, error) {
|
41 | 44 | }
|
42 | 45 | return newTbl, nil
|
43 | 46 | }
|
| 47 | + |
| 48 | +// String writes the table out to a CSV string. |
| 49 | +func (tbl *Table) String(comma rune, useCRLF bool) (string, error) { |
| 50 | + var b bytes.Buffer |
| 51 | + w := csv.NewWriter(&b) |
| 52 | + w.Comma = comma |
| 53 | + w.UseCRLF = useCRLF |
| 54 | + defer w.Flush() |
| 55 | + |
| 56 | + if len(tbl.Columns) > 0 { |
| 57 | + if err := w.Write(tbl.Columns); err != nil { |
| 58 | + return "", fmt.Errorf("error writing columns to csv [%s]", |
| 59 | + strings.Join(tbl.Columns, ",")) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + for _, row := range tbl.Rows { |
| 64 | + if err := w.Write(row); err != nil { |
| 65 | + return "", fmt.Errorf("error writing row to csv [%s]", |
| 66 | + strings.Join(row, ",")) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + w.Flush() |
| 71 | + return b.String(), w.Error() |
| 72 | +} |
0 commit comments