Установить свойства столбца в Excel, используя PHP

0

Я пишу приложение, которое запускает запрос оракула и экспортирует данные в формате Excel. Проблема, с которой я столкнулся, - это столбец с именем Tran_code в файле excel, который должен быть 00. Когда мой код запускается и генерирует Excel, он печатает один 0 вместо 00.

Установка значения ячейки в массиве:

$_SESSION['report_values'][$sno][19]=  "'00"; //Setting cell value in an array

Настройка заголовков и значений в файл Excel

include_once("class.export_excel.php");
$excel_obj->setHeadersAndValues($_SESSION['report_header'],$_SESSION['report_values']); // 
$excel_obj->GenerateExcelFile();

class.export_excel.php

<?php
class ExportExcel
{
//variable of the class
var $titles=array();
var $all_values=array();
var $filename;

//functions of the class
function ExportExcel($f_name) //constructor
{
    $this->filename=$f_name;
}
function setHeadersAndValues($hdrs,$all_vals) //set headers and query
{

//$this->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_TEXT );
    $this->titles=$hdrs;
    $this->all_values=$all_vals;
}
function GenerateExcelFile() //function to generate excel file
{

    foreach ($this->titles as $title_val) 
    { 
        $header .= $title_val."\t"; 

    } 
    for($i=0;$i<sizeof($this->all_values);$i++) 
    { 
        $line = ''; 
        foreach($this->all_values[$i] as $value) 
        { 
            if ((!isset($value)) OR ($value == "")) 
            { 
                $value = "\t"; 
            } //end of if
            else 
            { 

                $value = str_replace('"', '""', $value); 
                $value = '"' . $value . '"' . "\t"; 
            } //end of else
            $line .= $value; 
        } //end of foreach
        $data .= trim($line)."\n"; 
    }//end of the while 
    $data = str_replace("\r", "", $data); 
    if ($data == "") 
    { 
        $data = "\n(0) Records Found!\n"; 
    } 
    //echo $data;
    header("Content-type: application/vnd.ms-excel"); 
    header("Content-Disposition: attachment; filename=$this->filename"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    print "$header\n$data";  


}

}
?>
Теги:
excel
php-5.3

1 ответ

0

Я уверен, что вам понадобится использовать librayr, например PHPExcel, потому что вы в настоящее время работаете с TSV файлом, поэтому, когда Excel читает его, он попытается отформатировать столбцы на основе содержимого и, поскольку все его число будет отформатировать как один 0.

Таким образом, используя PHPExcel:

class ExportExcel
{
    //variable of the class
    protected $titles=array();
    protected $all_values=array();
    protected $filename;
    protected $dataTypes;

    //functions of the class
    function ExportExcel($f_name) //constructor
    {
        $this->filename=$f_name;
    }

    function setHeadersAndValues($hdrs,$all_vals, $dataTypes = array()) 
    {

        $this->titles=$hdrs;
        $this->all_values=$all_vals;
        $this->dataTypes = $dataTypes;
    }

    function getDataType($columnIndex) {
        // the data types tou provide should match up with
        // the constants on PHPExcel_Cell_DataType
        // https://github.com/PHPOffice/PHPExcel/blob/develop/Classes/PHPExcel/Cell/DataType.php
        if (isset($this->dataTypes[$columnIndex]) && !empty($this->dataTypes[$columnIndex])) {
            return $this->dataTypes[$columnIndex]
        }

        return null;
    }

    function GenerateExcelFile() //function to generate excel file
    {


        $excel = new PHPExcel();
        $worksheet = $excel->createSheet();

        // we will check for records here
        if (count($this->all_values)) {

            foreach (array_values($this->titles) as $col => $title_val) 
            { 
                // note values will be converted here so if you have you 00
                // in a header youll need to use the Explicit version like i do
                // below
                $worksheet->setCellValueByColumnAndRow($col, 1, $title_val);
            }

            $nbValues = count($this->all_values); 
            for($i=0; $i < $nbValues; $i++) 
            { 
                // for some reason rows are 1 indexed instead of 0
                // and we already used one row for the headers so
                // we add 2 to the increment to get the proper row index
                $row = $i+2; 

                foreach(array_values($this->all_values[$i]) as $col => $value) 
                { 
                    // note the use of the new method getDataType on your class
                    if (null !== ($type = $this->getDataType($col))) {
                        $worksheet->setCellValueExplicitByColumnAndRow($col, $row, $value, $type);
                    } else {
                        // type was null so let excel figure it out
                        $worksheet->setCellValueByColumnAndRow($col, $row, $value);
                    }
                } //end of foreach

            } //end of the for

            // we need to save it first so we can read the file data out to the user
            $writer = PHPExcel_IOFactory::createWriter($excel, "Excel5");
            $tmpfile = tempnam(sys_get_temp_dir(), 'report');
            $writer->save($tmpfile);

            $data = file_get_contents($tmpfile);
        } else {
            $data = "\n(0) Records Found!\n"; 
        }


        header("Content-type: application/vnd.ms-excel"); 
        header("Content-Disposition: attachment; filename=$this->filename"); 
        header("Pragma: no-cache"); 
        header("Expires: 0"); 
        print "$data";  
    }
}

Поэтому следует отметить, что вы можете настроить тип данных для данной группы ячеек, а не использовать методы setCellValueExplicit*, но я не помню, как это сделать, и не нашел его на первый взгляд в документах. Это может быть лучшим способом, но и работать.

  • 0
    это не работает!
  • 0
    Конкретные ошибки / предупреждения ??? Или вы говорите, что когда вы открываете файл, он все равно изменяет их на 0 ? А какой тип данных вы использовали?
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню