Excel正在从CSV文件中删除前导0

时间:2014-07-07 13:55:10

标签: excel csv dataformat autocorrect

它认为Excel正在剥离领先的0。我被告知在导出过程中将列格式更新为文本将修复此问题并修改Excel输出(来自" ProofAndTracking actionIpromoteuAutomation"文件,但我无法找到此文件或如何访问生成excel格式代码)。

我从未使用过Excel。我试过这个,但它似乎是一个本地修复: http://excelribbon.tips.net/T010262_Handling_Leading_Zeros_in_CSV_Files.html 有人能指出我正确的方向开始吗?

我已经研究过这些答案How to stop the leading 0's from being stripped off when exporting to excel from a datatable?Export Excel : Avoid stripping the leading zeros 提前谢谢!

这是我认为导致问题的功能,但还不确定如何在此处将列格式化为文本。 / *      *格式并发送订单和跟踪信息(通过Excel电子表格)为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' => 'donotreply@hitpromo.net',
        'from_name' => 'Hit Promotional Products',
        'subject' => 'Order Tracking Information - ' . date('m/d/Y'),
        'to_emails' => 'orders@ipromoteu.com',
        '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;
}

1 个答案:

答案 0 :(得分:16)

好的,Excel可以将csv列创建为text,但问题在于导入。

当Excel打开csv文件时,它“帮助”将任何看起来像数字的东西转换为数字,剥离前导零。

首先确保Excel正在导出它,在文本编辑器中打开文件并检查前导零是否存在。

您可能需要更改文件的导入方式。而不是只需双击csv文件,他们需要运行数据导入向导:

导入'来自文字'

From Text

选择分隔

Next

确保勾选逗号

Comma separator

选择列为文本

Select text

这应解决另一方面的问题。

另一种方法是在数字之前添加单个撇号',但如果他们使用宏/软件与文件进行交互,则可能会破坏该数据。

修改

在查看PHP代码(我无法测试)后,您可以更改该行:

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

要:

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

然而,当您导出时仍然可以删除它,因为它在技术上仍然是一个数字,格式将被删除。