35b3c732创建于 2025年5月15日历史提交
// EXEC: cjc %import-path %L %l %f
// EXEC: ./main
import stdx.serialization.serialization.*
import stdx.encoding.json.*
import std.collection.*
import std.io.*
import std.posix.*
import csv4cj.*
import std.env.*

main() {
    println("Csv输出:")
    csvPrint()
    printHeader()
    printSpecialCols()
    PrintWithNoneMode()
    printWithComment()
    return 0
}

public func printWithComment(): Unit {
    let csvRecord = CSVRecord(["1", "taobao", "小米", "200斤"], "注释\r\n第二行")
    let format = CSVOutFormat.DEFAULT
    let csvPrint = CSVPrinter(format)
    let sb = StringBuilder()

    csvPrint.printWithComment(csvRecord, sb)
}

func printHeader() {
    let header = ["姓名", "年龄", "学号", "成绩"]
    let outFormat = CSVOutFormat.DEFAULT.setHeader(header)

    let csvPrint = CSVPrinter(outFormat)
    let output = getStdOut()
    csvPrint.printHeader(output)
    csvPrint.printLine(output)
    csvPrint.printLine(["赵林", "15", "06", "89"], output)
    csvPrint.printLine(["李帅", "16", "15", "92"], output)
    csvPrint.print(["唐明", "15", "36", "61"], output)
}

func printSpecialCols(): Unit {
    let format = CSVOutFormat.DEFAULT.setQuoteMode(QuoteMode.CfgCols).setQuotedColsIndex([1, 2])
    let csvPrint = CSVPrinter(format)
    let sb = StringBuilder()
    csvPrint.print(["abc,", "1\\2,3", "a\tb", ","], sb)
}

func PrintWithNoneMode(): Unit {
    let format = CSVOutFormat.DEFAULT.setQuoteMode(QuoteMode.None)
    let csvPrint = CSVPrinter(format)
    let sb = StringBuilder()

    csvPrint.print(["abc", "a\r\nb\nc", "a\tb", ","], sb)

    var csvRecord = CSVRecord(["1", "a", "cangjie", "开发"], "注释")
    csvPrint.print(csvRecord, sb)
}

//按照csv格式输出
func csvPrint() {
    let csvContent = 
        ###"# Comment before header\\n
author,title,publishDate\\r
Dan Simmons|,Hyperion,"1989"
# Comment Line 1
# Comment Line 2|
# Comment Line 3|
Douglas ||Adams,The Hitchhiker's \"Guide\" to the Galaxy,1979
你好"###

    //创建字符串流
    let readerStream = StringStream(csvContent)

    let reader = CSVReader(readerStream)

    //创建格式化的解析参数
    let format: CSVParseFormat = CSVParseFormat.DEFAULT

    //创建解析器
    let csvParser = CSVParser(reader, format)

    let recordList = csvParser.getRecords()
    let outFormat = CSVOutFormat.DEFAULT.setQuoteMode(All).setDelimiter("|")
    let outFormat2 = CSVOutFormat.DEFAULT.setQuoteMode(QuoteMode.None).setDelimiter("||")
    let sbOut = StringBuilder()
    let csvPrint = CSVPrinter(outFormat)
    let csvPrint2 = CSVPrinter(outFormat2)

    var firstLine = true

    //遍历每一行解析记录
    for (csvRecord in recordList) {
        if (firstLine) {
            firstLine = false
            csvPrint.print(csvRecord, sbOut)
            csvPrint2.print(csvRecord, sbOut)
        } else {
            csvPrint.printLine(sbOut)
            csvPrint2.printLine(sbOut)
            csvPrint.print(csvRecord, sbOut)
            csvPrint2.print(csvRecord, sbOut)
        }
    }
    println(sbOut.toString())
}