1
// Copyright 2011 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
16
// A Writer writes records to a CSV encoded file.
18
// As returned by NewWriter, a Writer writes records terminated by a
19
// newline and uses ',' as the field delimiter. The exported fields can be
20
// changed to customize the details before the first call to Write or WriteAll.
22
// Comma is the field delimiter.
24
// If UseCRLF is true, the Writer ends each record with \r\n instead of \n.
25
// just \n is written.
27
Comma int // Field delimiter (set to to ',' by NewWriter)
28
UseCRLF bool // True to use \r\n as the line terminator
32
// NewWriter returns a new Writer that writes to w.
33
func NewWriter(w io.Writer) *Writer {
36
w: bufio.NewWriter(w),
40
// Writer writes a single CSV record to w along with any necessary quoting.
41
// A record is a slice of strings with each string being one field.
42
func (w *Writer) Write(record []string) (err os.Error) {
43
for n, field := range record {
45
if _, err = w.w.WriteRune(w.Comma); err != nil {
50
// If we don't have to have a quoted field then just
51
// write out the field and continue to the next field.
52
if !w.fieldNeedsQuotes(field) {
53
if _, err = w.w.WriteString(field); err != nil {
58
if err = w.w.WriteByte('"'); err != nil {
62
for _, rune := range field {
65
_, err = w.w.WriteString(`""`)
68
err = w.w.WriteByte('\r')
72
_, err = w.w.WriteString("\r\n")
74
err = w.w.WriteByte('\n')
77
_, err = w.w.WriteRune(rune)
84
if err = w.w.WriteByte('"'); err != nil {
89
_, err = w.w.WriteString("\r\n")
91
err = w.w.WriteByte('\n')
96
// Flush writes any buffered data to the underlying io.Writer.
97
func (w *Writer) Flush() {
101
// WriteAll writes multiple CSV records to w using Write and then calls Flush.
102
func (w *Writer) WriteAll(records [][]string) (err os.Error) {
103
for _, record := range records {
104
err = w.Write(record)
113
// fieldNeedsQuotes returns true if our field must be enclosed in quotes.
114
// Empty fields, files with a Comma, fields with a quote or newline, and
115
// fields which start with a space must be enclosed in quotes.
116
func (w *Writer) fieldNeedsQuotes(field string) bool {
117
if len(field) == 0 || strings.IndexRune(field, w.Comma) >= 0 || strings.IndexAny(field, "\"\r\n") >= 0 {
121
rune, _ := utf8.DecodeRuneInString(field)
122
return unicode.IsSpace(rune)