Tuesday, April 22, 2025
HomeGolangDealing with Semicolons in CSV to Forestall Splitting Throughout Cells in Go...

Dealing with Semicolons in CSV to Forestall Splitting Throughout Cells in Go – Technical Dialogue


I’m producing a CSV file in a Go HTTP handler and sending it as a response. A few of my textual content fields include semicolons (;), which causes points when opening the file in functions like Excel. The information is getting break up into a number of cells as an alternative of showing in a single cell.

For instance, in my case:

  • The identify subject incorporates google;gmail
  • The URL subject incorporates https://www.goo;gle.com/

Right here’s my present Go code:

func routeReferencesCrossrefDownloadPost(w http.ResponseWriter, r *http.Request) {
	var req DownloadRequest
	if err := json.NewDecoder(r.Physique).Decode(&req); err != nil {
		fmt.Println("JSON Decode Error:", err)
		http.Error(w, "Invalid request", http.StatusBadRequest)
		return
	}

	w.Header().Set("Content material-Sort", "textual content/csv")
	w.Header().Set("Content material-Disposition", `attachment; filename="search_items.csv"`)

	author := csv.NewWriter(w)
	defer author.Flush()

	author.Write([]string{"#", "Identify", "URL"})

	identify := "google;gmail"
	URL := "https://www.goo;gle.com/"
	for i := 0; i < 5; i++ {
		author.Write([]string{
			fmt.Sprintf("%d", i+1),
			identify,
			URL,
		})
	}
}

The semicolon in identify and URL is inflicting the textual content to separate throughout a number of cells as an alternative of staying inside one. I would like to not change any CSV settings in system. If I wrap values in double quotes ("), I shouldn’t see them explicitly within the CSV file when opened.

How can I be certain that values containing semicolons stay in the identical cell with out requiring the person to switch any settings of their CSV viewer?

It appears you might be utilizing semicolon as subject separator. Attempt utilizing comma as subject separator (I’m not certain however I believe it’s utilized by default)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments