development

PHP에서 Excel 파일 읽기

big-blog 2020. 9. 1. 07:51
반응형

PHP에서 Excel 파일 읽기


Excel 파일 (Office 2003)을 읽으려고합니다. 업로드해야하는 Excel 파일과 그 내용을 구문 분석해야합니다.

Google을 통해 Excel 파일 생성, Excel XML 파일 읽기, Excel CSV 파일 읽기 또는 불완전한 중단 된 프로젝트와 같은 관련 (및 불충분 한 주제)에 대한 답변 만 찾을 수 있습니다. 저는 Office 2003을 소유하고 있으므로 거기에서 파일이 필요한 경우 사용할 수 있습니다. 내 상자에 설치되어 있지만 공유 호스트에 설치되어 있지 않으며 설치할 수 없습니다.

편집 : 지금까지 모든 답변은 PHP-ExcelReader 및 / 또는 사용 방법에 대한 이 추가 기사가리 킵니다 .


PHP-ExcelReader사용 하여 xls 파일을 읽고 훌륭하게 작동합니다.


내가 아는 한 두 가지 선택이 있습니다.

  1. Office 2003 바이너리 형식을 알고있는 Spreadsheet_Excel_Reader
  2. Office 2003과 Excel 2007 (XML)을 모두 알고있는 PHPExcel . (링크를 따라 가면 이 라이브러리를 PHPSpreadSheet로 업그레이드 한 것을 볼 수 있습니다. )

PHPExcel은 Office 2003 형식으로 Spreadsheet_Excel_Reader를 사용합니다.

업데이트 : 한 번은 일부 Excel 파일을 읽어야했지만 Office 2003 XML 형식을 사용하여 파일을 읽고 응용 프로그램을 사용하는 사람들에게 해당 유형의 Excel 파일 만 저장하고 업로드하도록 지시했습니다.


Excel 파일의 데이터를 사용하려는 방법에 따라 다릅니다. mysql로 ​​가져 오려면 CSV 형식의 파일로 저장 한 다음 fgetcsv사용 하여 구문 분석하면됩니다.


XLSX (Excel 97-2003) https://github.com/shuchkin/simplexls 읽기

if ( $xls = SimpleXLS::parse('book.xls') ) {
    print_r( $xls->rows() );
} else {
    echo SimpleXLS::parseError();
}

XLSX (Excel 2003+) https://github.com/shuchkin/simplexlsx 읽기

if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
    print_r( $xlsx->rows() );
} else {
    echo SimpleXLSX::parseError();
}

산출

배열 (
    [0] => 어레이
        (
            [0] => ISBN
            [1] => 제목
            [2] => 저자
            [3] => 게시자
            [4] => ctry
        )
    [1] => 어레이
        (
            [0] => 618260307
            [1] => 호빗
            [2] => JRR 톨킨
            [3] => 휴튼 미 플린
            [4] => 미국
       )

)

CSV PHP 리더
https://github.com/shuchkin/simplecsv


이 시도...

다음 코드를 사용하여 "xls 및 xlsx"를 읽었습니다.

    <?php
    include 'excel_reader.php';       // include the class
    $excel = new PhpExcelReader;      // creates object instance of the class
    $excel->read('excel_file.xls');   // reads and stores the excel file data

    // Test to see the excel data stored in $sheets property
    echo '<pre>';
    var_export($excel->sheets);

    echo '</pre>';

    or 

 echo '<pre>';
    print_r($excel->sheets);

    echo '</pre>';

참조 : http://coursesweb.net/php-mysql/read-excel-file-data-php_pc


There is a great article to explain how to read/write excel files through php code, They have been recommend to use MS-Excel Stream Handler PHP class, which is one of the top class library for that :)


// Here is the simple code using COM object in PHP
class Excel_ReadWrite{

    private $XLSHandle;
    private $WrkBksHandle;
    private $xlBook;

    function __construct() {
        $this->XLSHandle = new COM("excel.application") or die("ERROR: Unable to instantaniate COM!\r\n"); 
    }

    function __destruct(){
        //if already existing file is opened
        if($this->WrkBksHandle != null)
        {   
            $this->WrkBksHandle->Close(True);
            unset($this->WrkBksHandle);
            $this->XLSHandle->Workbooks->Close();
        }
        //if created new xls file
        if($this->xlBook != null)
        {
            $this->xlBook->Close(True);
            unset($this->xlBook);
        }
        //Quit Excel Application
        $this->XLSHandle->Quit();
        unset($this->XLSHandle);
    }

    public function OpenFile($FilePath)
    {
        $this->WrkBksHandle = $this->XLSHandle->Workbooks->Open($FilePath);
    }

    public function ReadData($RowNo, $ClmNo)
    {
       $Value = $this->XLSHandle->ActiveSheet->Cells($RowNo, $ClmNo)->Value;
       return $Value;
    }  

    public function SaveOpenedFile()
    {
        $this->WrkBksHandle->Save(); 
    }  

    /***********************************************************************************
    * Function Name:- WriteToXlsFile() will write data based on row and column numbers
    * @Param:- $CellData- cell data
    * @Param:- $RowNumber- xlsx file row number
    * @Param:- $ColumnNumber- xlsx file column numbers
   ************************************************************************************/
   function WriteToXlsFile($CellData, $RowNumber, $ColumnNumber)
   {
       try{
               $this->XLSHandle->ActiveSheet->Cells($RowNumber,$ColumnNumber)->Value = $CellData;
           }
       catch(Exception $e){
               throw new Exception("Error:- Unable to write data to xlsx sheet");
           }
   }


   /****************************************************************************************
    * Function Name:- CreateXlsFileWithClmName() will initialize xls file with column Names
    * @Param:- $XlsColumnNames- Array of columns data
    * @Param:- $XlsColumnWidth- Array of columns width
   *******************************************************************************************/
   function CreateXlsFileWithClmNameAndWidth($WorkSheetName = "Raman", $XlsColumnNames = null, $XlsColumnWidth = null)
   {
       //Hide MS Excel application window
       $this->XLSHandle->Visible = 0;
       //Create new document
       $this->xlBook = $this->XLSHandle->Workbooks->Add();

       //Create Sheet 1
       $this->xlBook->Worksheets(1)->Name = $WorkSheetName;
       $this->xlBook->Worksheets(1)->Select;

       if($XlsColumnWidth != null)
       {
           //$XlsColumnWidth = array("A1"=>15,"B1"=>20);
           foreach($XlsColumnWidth as $Clm=>$Width)
           {
               //Set Columns Width
               $this->XLSHandle->ActiveSheet->Range($Clm.":".$Clm)->ColumnWidth = $Width;
           }    
       }
       if($XlsColumnNames != null)
       {
           //$XlsColumnNames = array("FirstColumnName"=>1, "SecondColumnName"=>2);
           foreach($XlsColumnNames as $ClmName=>$ClmNumber)
           {
               // Cells(Row,Column)
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Value = $ClmName;
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Font->Bold = True;
               $this->XLSHandle->ActiveSheet->Cells(1,$ClmNumber)->Interior->ColorIndex = "15";
           }
       }
   }
   //56 is for xls 8
    public function SaveCreatedFile($FileName, $FileFormat = 56)
    {
        $this->xlBook->SaveAs($FileName, $FileFormat);
    }

    public function MakeFileVisible()
    {
       //Hide MS Excel application window`enter code here`
       $this->XLSHandle->Visible = 1;
    }
}//end of EXCEL class

참고URL : https://stackoverflow.com/questions/563670/reading-an-excel-file-in-php

반응형