2014-04-01 7 views
8

मैं इस ऑब्जेक्ट को CSV फ़ाइल में कनवर्ट करना चाहता हूं। कॉलम नाम कुंजी होना चाहिए, यह सरणी का छोटा टुकड़ा है। और अंतिम सरणी केवल दयालु (कुंजी) में से एक होगी, अन्य सभी सरणी में एक ही कुंजी होगी लेकिन अलग-अलग मान होंगे।जावास्क्रिप्ट का उपयोग करके किसी ऑब्जेक्ट को CSV में कैसे परिवर्तित करता है?

[{ 
Comment: "Good", 
Experince Months: "4", 
Experince Years: "4", 
Score: "3", 
Subject: "CPP", 
Topic: "Scripting (mention details)" 
}, 
{ 
Comment: "Excilent", 
Experince Months: "6", 
Experince Years: "6", 
Score: "6", 
Subject: "CSharp", 
Topic: "WPF" 
}, 
{ 
Anything else worth highlighting: "Web Specialist", 
Result: "Selected", 
Total Business Analysis Experience: false, 
Total Project Management Experience: false, 
Total Score: 75, 
Total Server Side Development Experience: true, 
Total Server Side Support Experience: true, 
Total UI Development Experience: true, 
Total UI Support Experience: true 
}] 
+0

आप इस [कड़ी] को देखने के लिए चाहते हो सकता है (http://architects.dzone.com/articles/convert-javascript-object-csv)। – chris97ong

+0

मैं उस ऑब्जेक्ट की एक्सेल फ़ाइल बनाना चाहता हूं – User1038

+0

क्या आप जावास्क्रिप्ट द्वारा एक्सेल फ़ाइल बनाना चाहते हैं ??? –

उत्तर

8

यह एक सरल दिया गया है:

// Returns a csv from an array of objects with 
// values separated by tabs and rows separated by newlines 
function CSV(array) { 
    // Use first element to choose the keys and the order 
    var keys = Object.keys(array[0]); 

    // Build header 
    var result = keys.join("\t") + "\n"; 

    // Add the rows 
    array.forEach(function(obj){ 
     keys.forEach(function(k, ix){ 
      if (ix) result += "\t"; 
      result += obj[k]; 
     }); 
     result += "\n"; 
    }); 

    return result; 
} 
+0

का उपयोग कर रहा हूं केवल एक चीज - आप टीएसवी (टैब से अलग मूल्य) बनाते हैं, सीएसवी नहीं। यदि आपको सीएसवी की आवश्यकता है - कॉमा प्रतीक के साथ \ t को प्रतिस्थापित करें –

0

सीएसवी कनवर्टर

function ConvertToCSV(objArray) { 
     var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; 
     var str = ''; 

     for (var i = 0; i < array.length; i++) { 
      var line = ''; 
      for (var index in array[i]) { 
       if (line != '') line += ',' 

       line += array[i][index]; 
      } 

      str += line + '\r\n'; 
     } 

     return str; 
    } 
0

Anha के लिए JSON !! असल में मेरे पास PHP Class है जो same json object key (आप तीसरे सेट में भिन्न जेसन कुंजी का उपयोग कर रहे हैं) के साथ बहुत अच्छी तरह से काम करता है। इसलिए, यदि आप चाहें तो आप मेरे PHP Export Class को संशोधित कर सकते हैं जैसा कि आप चाहते हैं (विभिन्न ऑब्जेक्ट कुंजी के लिए)। यहां मैं उदाहरण समझाऊंगा और अपनी कक्षा को भी आपके साथ साझा करने जा रहा हूं। उम्मीद है, के बाद इस वर्ग को संशोधित अपनी इच्छा सच हो :)

PHP Export Class [Class.Export.php]

<?php 
/** 
* Class Export 
* 
* Send JSON data and make an array to save as Excel file 
* 
* @author neeraj.singh 
* @version 1.0 
* 
*/ 

// Class Start Here 
class Export { 

    /** 
    * Set Excel file name 
    * 
    * @var string 
    */ 
    public $filename = 'excel-doc'; 

    /** 
    * Set Excel field title 
    * 
    * @var string 
    */ 
    public $custom_titles; 

    /** 
    * Get JSON data and convert in Excel file 
    */ 
    public function saveAsExcel() { 
     $CSV = trim ($_POST ['exportdata']); 
     if (function_exists ('json_decode')) { 
      $data = json_decode ($CSV, true); 
      if (count ($data) > 0) { 
       // call excel export 
       $this->_createExcelByArray ($data); 
      } else { 
       die ("Sorry!! array not build."); 
      } 
     } else { 
      die ("Sorry!! json_decode not working on this server."); 
     } 
    } 

    /** 
    * Take an array and create 
    * Excel file 
    * 
    * @param array $dataArray   
    */ 
    private function _createExcelByArray($dataArray) { 
     // set excel file name 
     $this->filename = 'DEMO-Excel' . '-' . date ('d-m-Y-H-s'); 
     // get array field by first element of array 
     foreach ($dataArray [0] as $k => $v) { 
      $field [] = $k; 
     } 
     // get total no of field in array 
     $totalFields = count ($field); 
     $i = $j = 0; 
     // get array values 
     foreach ($dataArray as $v) { 
      for($j; $j < $totalFields; $j ++) { 
       $value [$i] [] = $v [$field [$j]]; 
      } 
      $i ++; 
      $j = 0; 
     } 
     $this->initExcel ($field, $value); 
    } 

    /** 
    * Creating an Excel file with array data 
    * 
    * @param array $titles   
    * @param array $array   
    */ 
    public function initExcel($titles, $array) { 
     $data = NULL; 
     if (! is_array ($array)) { 
      die ('The data supplied is not a valid array'); 
     } else { 
      $headers = $this->titles ($titles); 
      if (is_array ($array)) { 
       foreach ($array as $row) { 
        $line = ''; 
        foreach ($row as $value) { 
         if (! isset ($value) or $value == '') { 
          $value = "\t"; 
         } else { 
          $value = str_replace ('"', '""', $value); 
          $value = '"' . $value . '"' . "\t"; 
         } 
         $line .= $value; 
        } 
        $data .= iconv ("UTF-8", "GB18030//IGNORE", trim ($line)) . "\n"; 
       } 
       $data = str_replace ("\r", "", $data); 
       $this->generate ($headers, $data); 
      } 
     } 
    } 

    /** 
    * Create excel header and 
    * write data into file 
    * 
    * @param string $headers   
    * @param string $data   
    */ 
    private function generate($headers, $data) { 
     $this->set_headers(); 
     echo "$headers\n$data"; 
    } 

    /** 
    * Set Excel file field header 
    * 
    * @param array $titles   
    * @return string 
    */ 
    public function titles($titles) { 
     if (is_array ($titles)) { 
      $headers = array(); 
      if (is_null ($this->custom_titles)) { 
       if (is_array ($titles)) { 
        foreach ($titles as $title) { 
         $headers [] = iconv ("UTF-8", "GB18030//IGNORE", $title); 
        } 
       } else { 
        foreach ($titles as $title) { 
         $headers [] = iconv ("UTF-8", "GB18030//IGNORE", $title->name); 
        } 
       } 
      } else { 
       $keys = array(); 
       foreach ($titles as $title) { 
        $keys [] = iconv ("UTF-8", "GB18030//IGNORE", $title->name); 
       } 
       foreach ($keys as $key) { 
        $headers [] = iconv ("UTF-8", "GB18030//IGNORE", $this->custom_titles [array_search ($key, $keys)]); 
       } 
      } 
      return implode ("\t", $headers); 
     } 
    } 

    /** 
    * Set Response Header 
    */ 
    private function set_headers() { 
     $ua = $_SERVER ["HTTP_USER_AGENT"]; 
     $filename = $this->filename . ".xls"; 
     $encoded_filename = urlencode ($filename); 
     $encoded_filename = str_replace ("+", "%20", $encoded_filename); 
     header ("Pragma: public"); 
     header ("Expires: 0"); 
     header ("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
     header ("Content-Type: application/vnd.ms-excel; charset=UTF-8"); 
     header ("Content-Type: application/force-download"); 
     header ("Content-Type: application/octet-stream"); 
     header ("Content-Type: application/download"); 
     if (preg_match ("/MSIE/", $ua)) { 
      header ('Content-Disposition: attachment; filename="' . $encoded_filename . '"'); 
     } else if (preg_match ("/Firefox/", $ua)) { 
      header ('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"'); 
     } else { 
      header ('Content-Disposition: attachment; filename="' . $filename . '"'); 
     } 
     header ("Content-Transfer-Encoding: binary"); 
    } 
} 
// Class End Here 

ठीक है, HTML और PHP Code है प्रदर्शित करने के लिए कि यह कैसे काम करता है।

HTML Code:

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>JSON to Excel POC</title>  
    <script type="text/javascript"> 
    <!--  
    function excelExport() { 
     // this is your json data as string or you can 
     // use as object too 
     var jsonObject = '[{ "Comment" : "Good", "ExperinceMonths" : "4", "ExperinceYears" : "4", "Score" : "3", "Subject" : "CPP", "Topic" : "Scripting (mention details)" }, { "Comment" : "Excilent", "ExperinceMonths" : "6", "ExperinceYears" : "6", "Score" : "6", "Subject" : "CSharp", "Topic" : "WPF" }]';  
     // create a form 
     var form   = document.createElement('FORM'); 
     form.name   = 'exportform'; 
     form.id    = 'exportform'; 
     form.method   = 'POST'; 
     form.action   = './export.php'; 
     // create a hidden input inside form 
     var hiddenInput   = document.createElement('INPUT'); 
     hiddenInput.type = 'HIDDEN'; 
     hiddenInput.name = 'exportdata'; 
     hiddenInput.id  = 'exportdata'; 
     hiddenInput.value = jsonObject; 
     // insert hidden element inside form 
     form.appendChild(hiddenInput); 
     // insert form inside body 
     document.body.appendChild(form); 
     // submit the form 
     form.submit(); 
     // remoce the form 
     document.body.removeChild(form); 
     return true; 
    } 
    //--> 
    </script> 
    </head> 
<body> 
    <input type="button" value="Export" onClick='excelExport(); return false;'> 
</body> 
</html> 

और अंत में यहाँ

PHP Code [export.php]

<?php 
// add Class Export File 
require_once 'Class.Export.php'; 
// make a new onject of Class Export 
$export = new Export(); 
// Send POSt data to make 
// Excel File 
if(isset($_POST['exportdata'])){ 
    $export->saveAsExcel(); 
} 
?> 

आशा, कोड के इस खंड लोगों में मदद मिलेगी क्योंकि, शेयरिंग को हमेशा देखभाल है :) चीयर्स है !!

+0

हे आपकी मदद के लिए धन्यवाद, लेकिन मैं PHP का उपयोग नहीं कर रहा हूं, माफ करना मैंने पहले उल्लेख नहीं किया था, लेकिन मैं आपकी मदद की सराहना करता हूं। मैं जावास्क्रिप्ट – User1038

संबंधित मुद्दे

 संबंधित मुद्दे