如何将CSV文件加载到LiveCode堆栈中?

时间:2013-04-18 20:23:25

标签: csv livecode

假设我有fieldA,fieldB和fieldC的背景,我想将CSV文件加载到堆栈中。 CSV文件有三列A,B和C.“加载”按钮的脚本如何?

3 个答案:

答案 0 :(得分:2)

如果您只是想逐字加载内容,那么

on mouseUp
  put url ("file:" & pathToFile) into tContents
end mouseUp

会做到这一点。 要将列添加到字段中,您需要做更多的工作。一种方式:

on mouseUp
  put url ("file:" & pathToFile) into tContents
  -- set the itemDelimiter to tab -- if necessary
  repeat for each line tLine in tContents
    put item 1 of tLine & cr after field "fieldA"
    put item 2 of tLine & cr after field "fieldB"
    put item 3 of tLine & cr after field "fieldC"
  end repeat
end mouseUp

答案 1 :(得分:0)

如果数据是干净的,则CSV文件通常将字段分隔为“;”所以你可以用tab替换它们并使用“基本表字段”:

put url ("file:" & pathToFile) into tData
replace ";" with tab in tData
put tData into field "data"

如果您的数据是UTF8或其他内容,则需要先将其翻译。

答案 2 :(得分:0)

将数据读入变量lCsvData:

local lCsvData

on importCsv
  answer file "Chooose CSV file..."
  if it is not empty then
    put it into myPath
    put url ("binfile:" & myPath) into myData

现在我们可以解码数据:

    put urlDecode(urlEncode(myData,"UTF8")) into myData

问题:数据可以包含退货。让我们从项目中删除退货。如有必要,您可以单独处理每个项目。

    put empty into lCsvData
    set the itemDel to semicolon
    repeat for each line myLine in myData
      repeat for each item myItem in myLine
        put replaceText(myItem,cr,numToChar(14)) after lCsvData
      end repeat
      put cr after lCsvData
    end repeat
  end if
end importCsv

现在你有干净的数据。您可以选择一条线并将其放入一个字段中:

on showLine theLine
  put line theLine of of lCsvData into myLine
  set the itemDel to semicolon
  repeat for each item myItem in myLine
    put replaceText(myLine,numToChar(14),tab) into fld 1
  end repeat
end showLine

其中theLine是一个整数。您可以使用cr而不是tab,您可以以任何想要格式化输出字段的方式调整此脚本。