The OpenNET Project / Index page

[ новости /+++ | форум | теги | ]

Генерация XLS файлов на PHP (excel php web cgi)


<< Предыдущая ИНДЕКС Поиск в статьях src Установить закладку Перейти на закладку Следующая >>
Ключевые слова: excel, php, web, cgi,  (найти похожие документы)
Date: Mon, 21 Oct 2002 01:27:34 +0600 From: Eugeny Klimov <Eugeny_Klimov@p8.f201.n5010.z2.fidonet.org> Newsgroups: ftn.ru.php Subject: Генерация XLS файлов на PHP DB>> Ты бы лyчше pассказал в подpобностях, где y тебя пхп, и где DB>> эксель, и как ты собpался данные в эксель импоpтиpовать. MK> Пхп находится на сеpвеpе, ексель y пользователя. Hадо полyченные MK> двнные пpи запpосе вывести не веб фоpмy, а в екселовский лист. раз пять уже в эхе повторял. Вот пример класса, который генерит Excel5 таблицу, какую тебе надо: ==========Cut==================== <?php /**************************************************************** * Script : PHP Simple Excel File Generator - Base Class * Project : PHP SimpleXlsGen * Author : Erol Ozcan <eozcan@superonline.com> * Version : 0.1 * Copyright : GNU LGPL * URL : http://psxlsgen.sourceforge.net * Last modified : 17 May 2001 * Desciption : This class is used to generate very simple * MS Excel file (xls) via PHP. * The generated xls file can be obtained by web as a stream * file or can be written under $default_dir path. This package * is also included mysql, pgsql, oci8 database interaction to * generate xls files. * Limitations: * - Max character size of a text(label) cell is 255 * ( due to MS Excel 5.0 Binary File Format definition ) * * Credits : This class is based on Christian Novak's small * Excel library functions. ******************************************************************/ if( !defined( "PHP_SIMPLE_XLS_GEN" ) ) { define( "PHP_SIMPLE_XLS_GEN", 1 ); class PhpSimpleXlsGen { var $xls_data = ""; // where generated xls be stored var $default_dir = ""; var $filename = "psxlsgen"; // save filename var $fname = ""; // filename with full path var $crow = 0; // current row number var $ccol = 0; // current column number var $totalcol = 0; // total number of columns var $get_type = 0; // 0=stream, 1=file var $errno = 0; // 0=no error var $error = ""; // error string var $dirsep = "/"; // directory separator var $xls_stName = "Erol ╓zcan"; // Default constructor function PhpSimpleXlsGen() { $os = getenv( "OS" ); $temp = getenv( "TEMP"); // check OS and set proper values for some vars. if ( stristr( $os, "Windows" ) ) { $this->default_dir = $temp; $this->dirsep = "\\"; } else { // assume that is Unix/Linux $this->default_dir = "/tmp"; $this->dirsep = "/"; } // begin of the excel file header $this->xls_data = pack( "ssssss", 0x809, 0x08, 0x00,0x10, 0x0, 0x0 ); // WRITEACCESS: Write Access User Name /* $name = str_pad( $this->xls_stName, 111, " " ); $this->xls_data .= pack( "ss", 0x5c,0x70 ); $this->xls_data .= pack( "C", 10 ); $this->xls_data .= $name; */ } // end of the excel file function End() { $this->xls_data .= pack( "ss", 0x0A, 0x00 ); return; } // write a Number (double) into row, col function WriteNumber_pos( $row, $col, $value ) { $this->xls_data .= pack( "sssss", 0x0203, 14, $row, $col, 0x00 ); $this->xls_data .= pack( "d", $value ); return; } // write a label (text) into Row, Col function WriteText_pos( $row, $col, $value ) { $len = strlen( $value ); $this->xls_data .= pack( "s*", 0x0204, 8 + $len, $row, $col, 0x00, $len ); $this->xls_data .= $value; return; } // insert a number, increment row,col automatically function InsertNumber( $value ) { if ( $this->ccol == $this->totalcol ) { $this->ccol = 0; $this->crow++; } $this->WriteNumber_pos( $this->crow, $this->ccol, &$value ); $this->ccol++; return; } // insert a number, increment row,col automatically function InsertText( $value ) { if ( $this->ccol == $this->totalcol ) { $this->ccol = 0; $this->crow++; } $this->WriteText_pos( $this->crow, $this->ccol, &$value ); $this->ccol++; return; } // Change position of row,col function ChangePos( $newrow, $newcol ) { $this->crow = $newrow; $this->ccol = $newcol; return; } // new line function NewLine() { $this->ccol = 0; $this->crow++; return; } // send generated xls as stream file function SendFile( $filename ) { $this->filename = $filename; $this->SendFile(); } // send generated xls as stream file function SendFile() { $this->End(); header ( "Expires: Mon, 1 Apr 1974 05:00:00 GMT" ); header ( "Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT" ); header ( "Cache-Control: no-cache, must-revalidate" ); header ( "Pragma: no-cache" ); header ( "Content-type: application/x-msexcel" ); header ( "Content-Disposition: attachment; filename=$this->filename.xls" ); header ( "Content-Description: PHP Generated XLS Data" ); print $this->xls_data; } // change the default saving directory function ChangeDefaultDir( $newdir ) { $this->default_dir = $newdir; return; } // Save generated xls file function SaveFile( $filename ) { $this->filename = $filename; $this->SaveFile(); } // Save generated xls file function SaveFile() { $this->End(); $this->fname = $this->default_dir."$this->dirsep".$this->filename; if ( !stristr( $this->fname, ".xls" ) ) { $this->fname .= ".xls"; } $fp = fopen( $this->fname, "wb" ); fwrite( $fp, $this->xls_data ); fclose( $fp ); return; } function GetXls( $type = 0 ) { if ( !$type && !$this->get_type ) { $this->SendFile(); } else { $this->SaveFile(); } } } // end of the class PHP_SIMPLE_XLS_GEN } // end of ifdef PHP_SIMPLE_XLS_GEN
From: "Илья Карькин" <ilya@espb.ru> > Есть база в MySQL делаем к ней запpос из PHP как потом полyченные данные > автоматически всавить в Excel где пpойдет их дольней шая обpаботка? Вот пример по этомы поводу - открывается Excel с нужными данными или сохраняется файл: <? header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT"); header ("Cache-Control: no-cache, must-revalidate"); header ("Pragma: no-cache"); header ("Content-type: application/x-msexcel"); header ("Content-Disposition: attachment; filename=EmplList.xls" ); header ("Content-Description: PHP/INTERBASE Generated Data" ); xlsBOF(); // begin Excel stream xlsWriteLabel(0,0,"This is a label"); // write a label in A1, use for dates too xlsWriteNumber(0,1,9999); // write a number B1 xlsEOF(); // close the stream ?> <?php // ----- begin of function library ----- // Excel begin of file header function xlsBOF() { echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); return; } // Excel end of file footer function xlsEOF() { echo pack("ss", 0x0A, 0x00); return; } // Function to write a Number (double) into Row, Col function xlsWriteNumber($Row, $Col, $Value) { echo pack("sssss", 0x203, 14, $Row, $Col, 0x0); echo pack("d", $Value); return; } // Function to write a label (text) into Row, Col function xlsWriteLabel($Row, $Col, $Value ) { $L = strlen($Value); echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); echo $Value; return; } // ----- end of function library ----- ?>

<< Предыдущая ИНДЕКС Поиск в статьях src Установить закладку Перейти на закладку Следующая >>

Обсуждение [ Линейный режим | Показать все | RSS ]
  • 1.1, sil (?), 12:20, 22/01/2004 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    извиените дурака, но вот я создал php файл с первым указанным здесь кодом.
    в переменной $fname указал путь к файлу который я хочу получить в эксель а как это дело все запустить?
    то есть мой фай называется excel.php и я его вызываю но ничего не происходит....
    я раньше не работал с классами и не знаю как их вызывать к исполнению.
    помогите полжалуйста
     
  • 1.2, уку (?), 23:41, 06/02/2004 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    Смотри здесь может подойдет там все довольно просто http://plati.ru/asp/pay.asp?id_d=56586
     
  • 1.3, Andruhaa (?), 16:29, 04/11/2004 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    А как форматировать ичейки например мне нужно увиличить длину поля
     
     
  • 2.5, Виталий (??), 12:18, 17/01/2008 [^] [^^] [^^^] [ответить]  
  • +/
    или поставить "денежный" формат ячейки...
     

  • 1.4, Alexius (??), 14:30, 15/11/2006 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    Достаточно простой класс, а то я тут с PEAR разбирался на эту тему .... Если бы этот раньше нашёл, наверное склонился бы в его пользу но есть одно но ... PEAR генерит файлы формата excel 95, а там ограничение на длину поля 255 символов :( . Этот класс генерит нормальный формат, но символы после 255 преврашаются в ячейке в 'букозябры'. Может подскажете как этого избежать
     
  • 1.6, thomas (?), 06:29, 12/03/2008 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    Ребята, генерируйте xml...и любой формат поддерживается.
     
  • 1.7, Pasha (??), 14:57, 16/09/2008 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    А какнить тут можно страници разные в xsl создавать?
     
  • 1.8, SET (?), 17:18, 28/12/2008 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    клас приведенный Евгением Климовым работает вполне сносно за что огромное спасибо ему. Единственное что хотелось бы ответить - кажется из методов добавления данных InsertNumber и
    InsertText нужно убрать переход на след рядок:
               $this->crow++;
     
  • 1.9, SET (?), 17:23, 28/12/2008 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    простейший пример использования:

    $excel = new PhpSimpleXlsGen();
    $excel->default_dir = getcwd();
    $excel->fname='test.xls';
    $excel->InsertText('Kokashka');
    $excel->InsertText('Kokashka2');
    $excel->InsertText('Kokashka3');
    $excel->NewLine();
    $excel->InsertText('Kokashka');
    $excel->InsertText('Kokashka2');
    $excel->InsertText('Kokashka3');
    $excel->NewLine();
    $excel->InsertNumber(3);
    $excel->InsertNumber(4);
    $excel->InsertNumber(5);
    $excel->SaveFile('test.xls');

     
  • 1.10, Olfi (?), 22:04, 17/04/2009 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    а что за функция pack ? Это специальная функция для генерации excel ? Устанавливать куакие-нибудь библиотеки надо чтобы ексель генерировать?
     
  • 1.11, nikalas9 (?), 18:03, 14/05/2009 [ответить] [﹢﹢﹢] [ · · · ]  
  • +1 +/
    хотелось бы задать ширину таблиц, т.к. файл будет открываться для печати
     
  • 1.13, Sergey444 (?), 17:49, 17/06/2010 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    вначале выдаем такие заголовки:

    header("Content-Disposition: attachment;filename=excel.xls");
    header("Connection: Keep-Alive");
    header("Content-Type: application/vnd.ms-excel");

    а после выдаем простейший HTML с одной таблицей, при этом получаем файл который открывается в екселе.
    правда версия 2007 ругается что открываемый формат не екселевский и задает вопрос а Вы действительно хотите открыть этот файл который не екселевский? на что отвечаем да и радуемся.(проверял при всех установленных компонентах)

     
  • 1.14, sterlibash (?), 19:06, 20/07/2010 [ответить] [﹢﹢﹢] [ · · · ]  
  • +/
    Как передать в Эксель перенос текста по строкам. После того как файл будет сформирован, чтобы был соблюдён такой же перенос по строкам, как и в исходном тесте, который писали например через веб-форму.
     

    игнорирование участников | лог модерирования

     Добавить комментарий
    Имя:
    E-Mail:
    Заголовок:
    Текст:




    Партнёры:
    PostgresPro
    Inferno Solutions
    Hosting by Hoster.ru
    Хостинг:

    Закладки на сайте
    Проследить за страницей
    Created 1996-2024 by Maxim Chirkov
    Добавить, Поддержать, Вебмастеру