使用PHPExcel函数的日期和日期时间在Excel中以文本形式写入 [英] Date and Datetime using PHPExcel function writes in excel as Text

查看:123
本文介绍了使用PHPExcel函数的日期和日期时间在Excel中以文本形式写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PHPExcel函数有问题,这是我的代码:

<?php
# Load slim WP
define( 'WP_USE_THEMES', false );
require( './wp-load.php' );
# http://phpexcel.codeplex.com/
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
global $wpdb;
$query = "Select
  tsales_funnel.ID As ID,
  wp_users.display_name As Darijuma_vaditajs,
  tcportal_starpnieks.Cp_Name As Starpnieks,
  tcportal_stucture.Cp_Name As OWCA,
  n_products.Product_Nos As Produkts,
  tsales_funnel_mrecord.Product_type as Produkta_kods,
    tsales_funnel.Sanems_date as Saņēmšanas_datums,
  tsales_funnel_mrecord.Deadline As Deadline,
  n_sf_statusi.nosaukums_lv As Statuss,
  tsales_funnel_clients.Reg_nr As Klienta_Regnr,
  tfirmas_reg.name_in_quotes As Klients,
  tsales_funnel_mrecord.Faze_date as Faze_date,
  n_sf_fazes.nosaukums_lv As Faze,
  tsales_funnel_mrecord.Summa As Apdrošīnājuma_summa,
  tsales_funnel_mrecord.Vien_skaits As TRL_skaits,
  tsales_funnel_mrecord.Compensa_cena,
  tsales_funnel_mrecord.Tirgus_cena,
  wp_users02.display_name As Riska_parakstitajs,
  comm.Comment as Aizveršanas_komentārs
From
  tsales_funnel Left Join
  tsales_funnel_mrecord On tsales_funnel.ID = tsales_funnel_mrecord.Funnel_ID
  Left Join
  tcportal_starpnieks On tcportal_starpnieks.Cp_code = tsales_funnel.Starpnieks
  Left Join
  tcportal_stucture On tcportal_stucture.Cp_code = tsales_funnel.OWCA Left Join
  tsales_funnel_clients On tsales_funnel_clients.Funnel_ID = tsales_funnel.ID
  Left Join
  tfirmas_reg On tfirmas_reg.regcode = tsales_funnel_clients.Reg_nr Left Join
  wp_users On tsales_funnel.Darijuma_vaditajs = wp_users.user_login Left Join
  n_sf_statusi On n_sf_statusi.id = tsales_funnel.Statuss
  Left Join n_sf_fazes on tsales_funnel_mrecord.Product_faze = n_sf_fazes.id
   Left Join
  n_products On tsales_funnel_mrecord.Product_type = n_products.Product_Code
  Left Join
  (SELECT * FROM tsales_funnel_comments WHERE Comm_type = 4) as comm On tsales_funnel.ID = comm.Funnel_ID
  Left Join
  wp_users As wp_users02
    On wp_users02.user_login = tsales_funnel_mrecord.Risk_acceptance
WHERE 
tsales_funnel_clients.Tips_Galvenais = 1
";
$error = "Error: the query failed...
    <pre style='width:700px;word-wrap:break-word;white-space:normal;'>$query</pre>";
$result = $wpdb->get_results( $query, ARRAY_A ) or wp_die( $error );
$objPHPExcel = new PHPExcel(); 
$objPHPExcel->getProperties()
        ->setCreator("user")
            ->setLastModifiedBy("user")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 0; 
// Sheet cells
$cell_definition = array(
    'A' => 'ID',
    'B' => 'Darijuma_vaditajs',
    'C' => 'Starpnieks',
    'D' => 'OWCA',
    'E' => 'Produkts',
    'F' => 'Produkta_kods',
    'G' => 'Saņēmšanas_datums',
    'H' => 'Deadline',
    'I' => 'Statuss',
    'J' => 'Klienta_Regnr',
    'K' => 'Klients',
    'L' => 'Faze_date',
    'M' => 'Faze',
    'N' => 'Apdrošīnājuma_summa',
    'O' => 'TRL_skaits',
    'P' => 'Compensa_cena',
    'Q' => 'Tirgus_cena',
    'R' => 'Riska_parakstitajs',
    'S' => 'Aizveršanas_komentārs'
);
// Build headers
foreach( $cell_definition as $column => $value )
    $objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value ); 
// Build cells
while( $rowCount < count($result) ){ 
    $cell = $rowCount + 2;
    foreach( $cell_definition as $column => $value ){
        switch($column) {
            case 'G';
            case 'H';
            $val = '=DATEVALUE("'.date('Y.m.d',strtotime($result[$rowCount][$value])).'")';
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        break;
        case 'L';
        $val = date('Y.m.d H:i:s',strtotime($result[$rowCount][$value]));
        $objPHPExcel->getActiveSheet()->getStyle($column.$cell)
            ->getNumberFormat()
            ->setFormatCode("yyyy.mm.dd h:mm");
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        break;
        default;
        $val = $result[$rowCount][$value];
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        }
        }
    $rowCount++; 
} 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="iPortal_Atskaite_'.date('Y-m-d_H.i.s', strtotime('+3 hour')).'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;

我正在为列使用开关,在这里我需要其他单元格格式.

G列和H列需要格式2015.10.05(yyyy.mm.dd),L列需要2015.10.05 12:03(yyyy.mm.dd H:i).

函数getStyle()不起作用,并返回相同的值.如果输出为= datevalue(这是excel函数),则一切正常,但是随着时间的流逝将无法正常工作.

此外,如果我按excel中的edit单元格并按Enter,则该日期将转换为excel的正常日期,并且一切正常.

因此,问题出在输出格式化上.我该如何定义?对于其他列,例如数字,一切正常.

解决方案

您需要将日期和日期/时间转换为MS Excel序列化的日期时间戳....MS Excel不会自动为您将字符串转换为日期,只是简单地设置样式也不会以任何方式更改存储在单元格中的实际值(在您的情况下为字符串).

PHPExcel在PHPExcel_Shared_Date类中提供了几种不同的方法,使您可以进行这些转换.

$dto = new DateTime($result[$rowCount][$value]);
$dateVal = PHPExcel_Shared_Date::PHPToExcel($dto);
$objPHPExcel->getActiveSheet()->getStyle($column.$cell)
    ->getNumberFormat()
    ->setFormatCode("yyyy.mm.dd h:mm");
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $dateVal);

I have a problem with PHPExcel function, this is my code:

<?php
# Load slim WP
define( 'WP_USE_THEMES', false );
require( './wp-load.php' );
# http://phpexcel.codeplex.com/
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
global $wpdb;
$query = "Select
  tsales_funnel.ID As ID,
  wp_users.display_name As Darijuma_vaditajs,
  tcportal_starpnieks.Cp_Name As Starpnieks,
  tcportal_stucture.Cp_Name As OWCA,
  n_products.Product_Nos As Produkts,
  tsales_funnel_mrecord.Product_type as Produkta_kods,
    tsales_funnel.Sanems_date as Saņēmšanas_datums,
  tsales_funnel_mrecord.Deadline As Deadline,
  n_sf_statusi.nosaukums_lv As Statuss,
  tsales_funnel_clients.Reg_nr As Klienta_Regnr,
  tfirmas_reg.name_in_quotes As Klients,
  tsales_funnel_mrecord.Faze_date as Faze_date,
  n_sf_fazes.nosaukums_lv As Faze,
  tsales_funnel_mrecord.Summa As Apdrošīnājuma_summa,
  tsales_funnel_mrecord.Vien_skaits As TRL_skaits,
  tsales_funnel_mrecord.Compensa_cena,
  tsales_funnel_mrecord.Tirgus_cena,
  wp_users02.display_name As Riska_parakstitajs,
  comm.Comment as Aizveršanas_komentārs
From
  tsales_funnel Left Join
  tsales_funnel_mrecord On tsales_funnel.ID = tsales_funnel_mrecord.Funnel_ID
  Left Join
  tcportal_starpnieks On tcportal_starpnieks.Cp_code = tsales_funnel.Starpnieks
  Left Join
  tcportal_stucture On tcportal_stucture.Cp_code = tsales_funnel.OWCA Left Join
  tsales_funnel_clients On tsales_funnel_clients.Funnel_ID = tsales_funnel.ID
  Left Join
  tfirmas_reg On tfirmas_reg.regcode = tsales_funnel_clients.Reg_nr Left Join
  wp_users On tsales_funnel.Darijuma_vaditajs = wp_users.user_login Left Join
  n_sf_statusi On n_sf_statusi.id = tsales_funnel.Statuss
  Left Join n_sf_fazes on tsales_funnel_mrecord.Product_faze = n_sf_fazes.id
   Left Join
  n_products On tsales_funnel_mrecord.Product_type = n_products.Product_Code
  Left Join
  (SELECT * FROM tsales_funnel_comments WHERE Comm_type = 4) as comm On tsales_funnel.ID = comm.Funnel_ID
  Left Join
  wp_users As wp_users02
    On wp_users02.user_login = tsales_funnel_mrecord.Risk_acceptance
WHERE 
tsales_funnel_clients.Tips_Galvenais = 1
";
$error = "Error: the query failed...
    <pre style='width:700px;word-wrap:break-word;white-space:normal;'>$query</pre>";
$result = $wpdb->get_results( $query, ARRAY_A ) or wp_die( $error );
$objPHPExcel = new PHPExcel(); 
$objPHPExcel->getProperties()
        ->setCreator("user")
            ->setLastModifiedBy("user")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 0; 
// Sheet cells
$cell_definition = array(
    'A' => 'ID',
    'B' => 'Darijuma_vaditajs',
    'C' => 'Starpnieks',
    'D' => 'OWCA',
    'E' => 'Produkts',
    'F' => 'Produkta_kods',
    'G' => 'Saņēmšanas_datums',
    'H' => 'Deadline',
    'I' => 'Statuss',
    'J' => 'Klienta_Regnr',
    'K' => 'Klients',
    'L' => 'Faze_date',
    'M' => 'Faze',
    'N' => 'Apdrošīnājuma_summa',
    'O' => 'TRL_skaits',
    'P' => 'Compensa_cena',
    'Q' => 'Tirgus_cena',
    'R' => 'Riska_parakstitajs',
    'S' => 'Aizveršanas_komentārs'
);
// Build headers
foreach( $cell_definition as $column => $value )
    $objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value ); 
// Build cells
while( $rowCount < count($result) ){ 
    $cell = $rowCount + 2;
    foreach( $cell_definition as $column => $value ){
        switch($column) {
            case 'G';
            case 'H';
            $val = '=DATEVALUE("'.date('Y.m.d',strtotime($result[$rowCount][$value])).'")';
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        break;
        case 'L';
        $val = date('Y.m.d H:i:s',strtotime($result[$rowCount][$value]));
        $objPHPExcel->getActiveSheet()->getStyle($column.$cell)
            ->getNumberFormat()
            ->setFormatCode("yyyy.mm.dd h:mm");
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        break;
        default;
        $val = $result[$rowCount][$value];
        $objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $val);
        }
        }
    $rowCount++; 
} 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="iPortal_Atskaite_'.date('Y-m-d_H.i.s', strtotime('+3 hour')).'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;

I'm using switch for columns, where I need a different cell format.

Column G and H I need format 2015.10.05 (yyyy.mm.dd) And for column L 2015.10.05 12:03 (yyyy.mm.dd H:i).

Function getStyle() doesn't work, and returns the same value. If output as =datevalue, which is excel function, all is ok, but it doesn't work with time.

Also, if I press edit cell in excel and press enter, that date converts to normal date for excel and all works fine.

So, the problem is with output formatting. How can I define it? For other columns, for example for numbers, all is ok.

解决方案

You need to convert your dates and date/times to an MS Excel serialized datetime stamp.... MS Excel does not automagically convert strings to dates for you, nor does simply setting a style change the actual value (a string in your case) that's stored in the cell in any way.

PHPExcel provides several different methods in the PHPExcel_Shared_Date class that will let you do these conversions.

$dto = new DateTime($result[$rowCount][$value]);
$dateVal = PHPExcel_Shared_Date::PHPToExcel($dto);
$objPHPExcel->getActiveSheet()->getStyle($column.$cell)
    ->getNumberFormat()
    ->setFormatCode("yyyy.mm.dd h:mm");
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $dateVal);

这篇关于使用PHPExcel函数的日期和日期时间在Excel中以文本形式写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆