2015-01-16 3 views
-2

로컬 CSV 파일의 여러 열에 포함 된 값을 사용하여 일부 InDesign 템플릿을 동적으로 생성하는 스크립트를 작성하려고합니다.비 - 웹 응용 프로그램에 대한 자바 스크립트로 CSV를 구문 분석 할 수 있습니까?

브라우저 응용 프로그램에 대해이 방법에 접근하는 방법은 여러 가지가 있지만 웹 응용 프로그램이 아닌 응용 프로그램에서는 찾을 수 없으며 모든 시도가 실패했습니다.

nb : Windows에서 데이터를 생성하고 Excel을 사용합니다. 내 리눅스 상자에 편집하고 맥에서 스크립트를 실행하므로 모든 것을 고려한 해결책이 필요하다. http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm

// target the latest version of InDesign 
#target "InDesign-10" 

// This will parse a delimited string into an array of 
// arrays. The default delimiter is the comma, but this 
// can be overriden in the second argument. 
// http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm 

function CSVToArray(strData, strDelimiter){ 
    // Check to see if the delimiter is defined. If not, 
    // then default to comma. 
    strDelimiter = (strDelimiter || ","); 
    // Create a regular expression to parse the CSV values. 
    var objPattern = new RegExp(
     (
      // Delimiters. 
      "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + 
       // Quoted fields. 
       "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + 
       // Standard fields. 
       "([^\"\\" + strDelimiter + "\\r\\n]*))" 
     ), 
     "gi" 
    ); 
    // Create an array to hold our data. Give the array 
    // a default empty first row. 
    var arrData = [[]]; 
    // Create an array to hold our individual pattern 
    // matching groups. 
    var arrMatches = null; 
    // Keep looping over the regular expression matches 
    // until we can no longer find a match. 
    while (arrMatches = objPattern.exec(strData)){ 
     // Get the delimiter that was found. 
     var strMatchedDelimiter = arrMatches[ 1 ]; 
     // Check to see if the given delimiter has a length 
     // (is not the start of string) and if it matches 
     // field delimiter. If id does not, then we know 
     // that this delimiter is a row delimiter. 
     if (
      strMatchedDelimiter.length && 
       (strMatchedDelimiter != strDelimiter) 
     ){ 
      // Since we have reached a new row of data, 
      // add an empty row to our data array. 
      arrData.push([]); 
     } 
     // Now that we have our delimiter out of the way, 
     // let's check to see which kind of value we 
     // captured (quoted or unquoted). 
     if (arrMatches[ 2 ]){ 
      // We found a quoted value. When we capture 
      // this value, unescape any double quotes. 
      var strMatchedValue = arrMatches[ 2 ].replace(
       new RegExp("\"\"", "g"), 
       "\"" 
      ); 
     } else { 
      // We found a non-quoted value. 
      var strMatchedValue = arrMatches[ 3 ]; 
     } 
     // Now that we have our value string, let's add 
     // it to the data array. 
     arrData[ arrData.length - 1 ].push(strMatchedValue); 
    } 
    // Return the parsed data. 
    return(arrData); 
} 

var csv = CSVToArray(File("source.csv"), ","); 

// create new document using specified presets 
var myDocument    = app.documents.add(); 
var myTextFrame    = myDocument.pages.item(0).textFrames.add(); 
myTextFrame.geometricBounds = ["6p", "6p", "24p", "24p"]; 
myTextFrame.contents  = csv[0]; 

없는 worky, 조언 간단한 경우를 들어

+0

"웹 이외의 응용 프로그램"이란 무엇을 의미합니까? 스크립트를 어떻게 실행 하시겠습니까? 마디? – atmd

+1

브라우저 응용 프로그램이 아닙니다. Adobe InDesign 용 스크립트입니다. ExtendScript Toolkit을 사용하여 실행됩니다. –

+1

실제 문제는 무엇입니까? 파일을 성공적으로 읽었으며 현재 변수에 포함 된 데이터에 대해 CSV 파서 만 필요합니까? – Quentin

답변

2

감사는 참으로 사소한 :

function parseCSV(text) { 
 
    return text.split('\n').map(function(row) { 
 
     var r = []; 
 
     row.replace(/""/g, "\x01").replace(/"(.*?)"|([^\s,]+)/g, function(_, $1, $2) { 
 
      r.push(($1 || $2).replace(/\x01/g, '"')); 
 
     }); 
 
     return r; 
 
    }); 
 
} 
 

 
// example: 
 

 
var t = 
 
    ' "lorem ipsum", dolor,      sit\n' + 
 
     ' consectetur, "adipiscing ""elit"" sed", eiusmod'; 
 

 
csv = parseCSV(t); 
 
document.write(JSON.stringify(csv));

내가 몇 가지 유용한 코드를 포함, 지금까지이 여기에서 찾을 것입니다

그러나 CSV가 비표준 일 경우 조금 더 어려울 것입니다. 어도비 스크립팅에서 csv 같은 노드 모듈을 사용할 수 있는지 모르겠다면, 적어도 소스를 살펴볼 수 있습니다.

+0

감사합니다. georg . 어떻게하면 내 source.csv 파일을 읽을 수 있습니까? 나는 내 자리에있는 것처럼 부르 겠어? "column 3"이라는 열의 5 행에서 어떻게 값을 읽습니까? –

+0

이 줄에서 런타임 오류가 발생합니다 : return text.split('\n').map(function(row) {