如何在ColdFusion

时间:2017-05-09 15:57:16

标签: coldfusion cfml railo lucee

我正在加载CSV,并尝试在MySQL中插入内容。其中一个字段中包含逗号,例如:

 "Jane Doe","Boston","None","Yes","No"
 "John Doe","New York","No garlic, onions, or nuts","Yes","No"
 "Mary Doe","New York","None","Yes","No"

我首先阅读文件:

<cffile action="read"file="/var/www/html/temp.csv" variable="datacsv"> 

然后我开始循环:

<cfloop index="index" list="#datacsv#" delimiters="#chr(13)#,#chr(10)#">
    <cfset item1 = Replace(listgetAt(index,1), """", "", "ALL")> #item1#<br>
    <cfset item2 = Replace(listgetAt(index,2), """", "", "ALL")> #item2#<br>
    <cfset item3 = Replace(listgetAt(index,3), """", "", "ALL")> #item3#<br>
    <cfset item4 = Replace(listgetAt(index,4), """", "", "ALL")> #item4#<br>
    <cfset item5 = Replace(listgetAt(index,5), """", "", "ALL")> #item5#<br>
</cfloop>

我的问题是,在第二个项目(John Doe)中,第三个字段中的那些逗号将被解析为新字段。所以我要么弄清楚我错过了什么导致了这个问题,要么删除任何字段中的逗号并用不同的字符替换它们。

2 个答案:

答案 0 :(得分:2)

尝试使用此正则表达式用破折号替换嵌入的逗号:

<cfscript>

    // CSV content
    csvContent = '"John Doe","New York","No garlic, onions, or nuts","Yes","No"';

    // Replace all comma in between with dash
    writeOutput(
        csvContent.replaceAll(
            ',(?!")|(?<!"),(?=[^"]*?"(?:,|\r?\n|\r|$))', '-'
        )
    );
</cfscript>

这是GIST

修改

  

这有效,但它也剥离了那里的任何CR / LF。当我遍历我的项目时,我正在做:<cfloop index="index" list="#csvContent#" delimiters="#chr(13)#,#chr(10)#">

您可以简单地使用CR / LF(chr(13)chr(10))作为分隔符。 这是一个例子:

<!--- CSV content --->
<cfset csvContent = '"John Doe","New York","No garlic, onions, or nuts","Yes","No"'>

<!--- Replace all comma in between with dash --->
<cfset newCsvContent = csvContent.replaceAll(
    ',(?!")|(?<!"),(?=[^"]*?"(?:,|\r?\n|\r|$))', '-'
)>

<!--- Process records --->
<cfoutput>
    <cfloop list="#newCsvContent#" index="csvRow" delimiters="#chr(13)##chr(10)#">
        Column 1: #replace( csvRow.listGetAt( 1 ), """", "", "ALL")#<br>
        Column 2: #replace( csvRow.listGetAt( 2 ), """", "", "ALL")#<br>
        Column 3: #replace( csvRow.listGetAt( 3 ), """", "", "ALL")#<br>
        Column 4: #replace( csvRow.listGetAt( 4 ), """", "", "ALL")#<br>
        Column 5: #replace( csvRow.listGetAt( 5 ), """", "", "ALL")#<br>
        <br>
    </cfloop>
</cfoutput>

答案 1 :(得分:2)

使用<cfhttp>代替<cffile>来读取文件。 name属性为您提供查询属性。 This document声明textQualifier的默认值是双引号,但无论如何我都会指定它。