简体   繁体   English

如何使用Golang从查询直接导出为CSV

[英]How to export to CSV directly from a query using golang

I have a java script that exports website html table contents to CSV from a Web Application. 我有一个Java脚本,可以从Web应用程序将网站html表内容导出到CSV。 I would like to bypass that and when a button is pressed it runs a query and downloads it to CSV without first loading it to the html table. 我想绕过它,当按下按钮时,它将运行查询并将其下载到CSV,而无需先将其加载到html表中。 Does anyone have anything like that? 有人有这样的东西吗?

This is useful for printing out reports. 这对于打印报告很有用。 Some big reports that i have since they have to load in the website first cause too much lag. 由于必须先加载到网站中,因此我必须先进行一些大型报告,这会导致过多的延迟。

You would just do something like: 您只需要执行以下操作:

func(w http.ResponseWriter, r *http.Request)
    var data = [][]string{{"Line1", "Hello"}, {"Line2", "World"}}
    buffer := &bytes.Buffer{} // creates IO Writer

    writer := csv.NewWriter(buffer)

    for _, value := range data {
        err := writer.Write(value)
        checkError("Cannot write to buffer", err)
    }

    writer.Flush()

    w.Header().Set("Content-Type", "text/csv") // setting the content type header to text/csv
    w.Header().Set("Content-Disposition", "attachment;filename=TheCSVFileName.csv")
    w.Write(buffer.Bytes())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM