2014-07-07 7 views
5

Crede che Excel stia eliminando gli 0 principali. Mi è stato detto che l'aggiornamento del formato della colonna in testo durante l'esportazione risolverà questo problema e modificherà l'output di Excel (proveniente dal file "ProofAndTracking actionIpromoteuAutomation", ma non riesco a trovare questo file o come accedere a dove viene generato il codice di formattazione excel) .Excel sta eliminando gli 0 dai file CSV

Non ho mai lavorato con Excel. Ho provato questo, ma sembra essere una correzione locale: http://excelribbon.tips.net/T010262_Handling_Leading_Zeros_in_CSV_Files.html Qualcuno potrebbe indicarmi la direzione giusta per iniziare?

Ho cercato queste risposte How to stop the leading 0's from being stripped off when exporting to excel from a datatable? e Export Excel : Avoid stripping the leading zeros
Grazie in anticipo!

Ecco la funzione che credo causi il problema, ma non ancora sicuro come formattare le colonne in testo qui./* * formato e l'ordine e le informazioni di tracciamento (tramite foglio di calcolo Excel) inviare per il giorno per ipromoteu (150837) */

public function actionIpromoteuAutomation() { 
    $ordersGroup1 = $this->getIpromoteuProof(); 
    $ordersGroup2 = $this->getIpromoteuProofHistory(); 
    $orders = array_merge($ordersGroup1, $ordersGroup2); 
    $fileName = 'Hit Promo Order Tracking ' . date('m-d-Y'); 
    $this->_export($orders, $fileName); 
    $fileName = $fileName . '.xls'; 
    $toIPROMOTEU = array(//email to be sent to HR when request is submitted 
     'body' => 'Attached, please find the Excel spreadsheet containing' 
     . ' order details for orders on ' . date('m/d/Y') . '.', 
     'from_email' => '[email protected]', 
     'from_name' => 'Hit Promotional Products', 
     'subject' => 'Order Tracking Information - ' . date('m/d/Y'), 
     'to_emails' => '[email protected]', 
     'attachments' => array(array('path' => Yii::app()->basePath . '/../tmp/' . $fileName, 'filename' => $fileName)), 
    ); 
    Hit::email((object) $toIPROMOTEU); 

    $this->logForDeveloper('Order records sent to iPromoteU for '. date('m/d/Y')); 
} 

private function _export($data, $fileName, $format = 'excel', $output = false) { 
    // get a reference to the path of PHPExcel classes 
    $phpExcelPath = Yii::getPathOfAlias('ext.phpexcel'); 

    // Turn off our yii library autoload 
    spl_autoload_unregister(array('YiiBase', 'autoload')); 
    include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php'); 

    // Create new PHPExcel object 
    $objPHPExcel = new PHPExcel(); 

    if ($format == 'excel') { 
     // Set properties 
     $objPHPExcel->getProperties()->setCreator(Yii::app()->user->name) 
       ->setLastModifiedBy(Yii::app()->user->name) 
       ->setTitle('Order Tracking Report'); 
    } 

    $styleArray = array(
     'font' => array(
      'bold' => true, 
      'underline' => true, 
     ) 
    ); 
    $objPHPExcel->setActiveSheetIndex(0); 
    $sheet = $objPHPExcel->getActiveSheet(); 

    for ($rowCounter = 0; $rowCounter < sizeof($data); $rowCounter++) { 
     $sheet->getStyle("A" . ($rowCounter + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); 
     $sheet->getStyle("B" . ($rowCounter + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); 
     $sheet->getStyle("C" . ($rowCounter + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); 
     $sheet->setCellValue("A" . ($rowCounter + 1), date('m/d/Y', strtotime($data[$rowCounter]['date']))); 
     //$sheet->setCellValue("A".($rowCounter+1), $data[$rowCounter]['date']); 
     if ($data[$rowCounter]['fedex_tracking'] != '') 
      $sheet->setCellValue("B" . ($rowCounter + 1), $data[$rowCounter]['fedex_tracking']); 
     else 
      $sheet->setCellValue("B" . ($rowCounter + 1), $data[$rowCounter]['other_tracking']); 
     $sheet->setCellValue("C" . ($rowCounter + 1), $data[$rowCounter]['sales_order_number']); 
     $sheet->getStyle("B" . ($rowCounter + 1))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER); 
    } 

    $sheet->setCellValue("A1", "DATE") 
      ->setCellValue("B1", "TRACKING") 
      ->setCellValue("C1", "PO NUMBER") 
      ->getStyle("A1:C1")->applyFromArray($styleArray); 

    ////Set the column widths 
    $sheet->getColumnDimension("A")->setWidth(25); 
    $sheet->getColumnDimension("B")->setWidth(25); 
    $sheet->getColumnDimension("C")->setWidth(25); 
    // Rename sheet 
    $objPHPExcel->getActiveSheet()->setTitle('Order Tracking Report'); 

    // Set active sheet index to the first sheet, 
    // so Excel opens this as the first sheet 
    $objPHPExcel->setActiveSheetIndex(0); 

    $fileName = $fileName . ($format == 'excel' ? '.xls' : '.csv'); 

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
    $path = Yii::app()->basePath . '/../tmp/' . $fileName; 
    $objWriter->save($path); 

    // Once we have finished using the library, give back the 
    // power to Yii... 
    spl_autoload_register(array('YiiBase', 'autoload')); 
} 

public function getIpromoteuProof() { 
    $date = date('Ymd'); 
    $db2params = Yii::app()->params['db2params']; 
    $db = Zend_Db::factory('Db2', $db2params); 
    $select = $db->select() 
      ->from(
        // table 
        array('t' => 'WBPIPRAE'), 
        // columns 
        array(
       'sales_order_number' => 'TRIM(WAESPO#)', 
        ), 
        // schema 
        $db2params['schemas']['hitdta']) 
      ->joinLeft(
        // table 
        array('f' => 'MFD1MD'), 'CONCAT(TRIM(WAEORD#),RIGHT(TRIM(MDORDR),3))=TRIM(MDORDR)', 
        // columns 
        array(
       'fedex_tracking' => 'TRIM(MDFTRK)', 
       'other_tracking' => 'TRIM(MDFBRC)', 
       'date' => 'TRIM(MDUPDT)', 
        ), 
        // schema 
        $db2params['schemas']['varfil']) 
      ->where("MDUPDT = '" . $date . "'") 
      ->where("WAEIVKY='150837'") 
      ->order('sales_order_number') 
      ->distinct(true); 

    $stmt = $db->query($select); 
    $orders = $stmt->fetchAll(); 
    return $orders; 
} 
+0

Stai cercando una soluzione per le esportazioni? Inoltre il file csv viene consumato SOLO da Excel o viene letto altrove? – bendataclear

+0

Ciao. Sì, a quanto pare il mio collega pensa che sia esportato e utilizzato solo da Excel. – DR1

+0

Provando questo codice ora, dopo molte ricerche !! commenti apprezzati .. // Formatta le colonne come testo per evitare la cattiva abitudine di stripping di Excel-- Strisce che portano '0' dai numeri. $ objPHPExcel-> getActiveSheet() -> setStyle (PHPExcel_Cell_DataType :: TYPE_STRING); – DR1

risposta

12

OK, Excel può creare le colonne CSV come text ma il problema è con il importare.

Quando Excel apre i file CSV, "utile" converte tutto ciò che assomiglia ad un numero in un numero, eliminando gli zero iniziali.

Accertarsi innanzitutto che Excel lo esporti come dovrebbe, aprire il file in un editor di testo e controllare che lo zero iniziale sia presente.

Probabilmente sarà necessario modificare la modalità di importazione del file. Invece di loro solo doppio clic sul file CSV, hanno bisogno di correre attraverso la procedura guidata di importazione dei dati:

Importa 'Dal testo'

From Text

Selezionare Delimitato

Next

Assicurarsi che la virgola sia selezionata

Comma separator

Selezionare la colonna come testo

Select text

Questo dovrebbe risolvere il problema sul lato opposto.

Un'altra alternativa è aggiungere un singolo apostrofo ' prima dei numeri, tuttavia se utilizzano macro/software per interagire con il file questo potrebbe interromperlo.

Modifica

Dopo aver guardato il codice PHP (non riesco a provare) si potrebbe essere in grado di cambiare la linea:

$sheet->getStyle("B" . ($rowCounter + 1))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER); 

A:

$sheet->getStyle("B" . ($rowCounter + 1))->getNumberFormat()->setFormatCode('000000000000'); // With however many zero's you need to keep 

Questo tuttavia può ancora essere rimosso quando si esporta poiché è ancora tecnicamente un numero e la formattazione verrà rimossa.

+0

Fatto, grazie, ma penso che sia da qualche parte formattato nel nostro codice php e che devo aggiornare il formato della colonna al testo durante l'esportazione. – DR1

+0

@ DR1 Lo zero iniziale manca quando si apre il file csv in un editor di testo? – bendataclear

+0

Sì, è per questo che pensiamo che abbiamo bisogno di formattare le colonne come testo. Si prega di vedere la funzione sopra dove penso che ho bisogno di farlo. – DR1

Problemi correlati