PHPExcel đọc tệp excel

Không có khái niệm mở tệp để đọc và ghi trong PHPExcel vì nó không biết nguồn của đối tượng PHPExcel. Bất kể nguồn từ nơi tệp được tải hoặc loại tệp, tệp có thể được đọc dựa trên tên của nó và được lưu với cùng tên. Bằng cách này, tệp sẽ bị ghi đè và những thay đổi mới sẽ được phản ánh trong tệp

Ví dụ

error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/London');
set_include_path(get_include_path() . PATH_SEPARATOR . './Classes/');
include 'PHPExcel/IOFactory.php';
$fileType = 'Excel5';
$fileName = name_of_file.xls';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objPHPExcel->setActiveSheetIndex(0)
   ->setCellValue('A1', 'Hello')
   ->setCellValue('B1', 'World!');
// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($fileName);

đầu ra

Điều này sẽ tạo ra đầu ra sau -

Changes to cell A1, B1 are reflected in the name_of_file.xls file.

Giới hạn thời gian được đặt thành 0 và múi giờ được đặt thành Châu Âu/London. Loại tệp được biết là Excel và tên tệp được gán cho biến 'tên tệp'. Lớp 'PHPExcel_IOFactory' 'createReader' được sử dụng để tạo đối tượng và nó được tải bằng hàm 'load'. Hai giá trị ô của trang tính 'xls' được thay đổi và nó được lưu với cùng tên

Đây là một câu trả lời rất gần đây cho câu hỏi này từ tập tin. 07người đọc. php

');

date_default_timezone_set('Europe/London');

/** Include PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';


if (!file_exists("05featuredemo.xlsx")) {
    exit("Please run 05featuredemo.php first." . EOL);
}

echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$callStartTime = microtime(true);

$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx");

$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo 'Call time to read Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;


echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$callStartTime = microtime(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;

echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;


// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;

// Echo done
echo date('H:i:s') , " Done writing file" , EOL;
echo 'File has been created in ' , getcwd() , EOL;

Nếu bạn cần sử dụng PHP để tạo và tương tác với ứng dụng bảng tính Excel của Microsoft thì sử dụng PHPExcel là một cách hay

PHPExcel là một thư viện được viết bằng PHP và có một tập hợp đầy đủ các lớp, cho phép bạn ghi và đọc từ các định dạng tệp bảng tính khác nhau, chẳng hạn như Excel (BIFF). XLS, Excel 2007 (OFFICEOPENXML). XLSX, CSV, LIBRE/OPENOFFICECALC. ODS, GNUMERIC, PDF và HTML. Vì PHPExcel không chỉ tương tác với MS Excel mà còn với các định dạng khác, nên có thể hơi khó để bắt đầu

Định dạng tệp đọc được hỗ trợ bao gồm

  • BIFF 5-8 (. XLS) Excel 95 trở lên
  • Văn phòng mở XML (. XLSX) Excel 2007 trở lên
  • Bảng tínhML (. XML) Excel 2003
  • Định dạng Tài liệu Mở/OASIS (. ODS)
  • GNUMERIC
  • HTML
  • SYLK
  • CSV

Quảng cáo

Các định dạng tệp ghi được hỗ trợ bao gồm

  • BIFF 8 (. XLS) Excel 95 trở lên
  • Văn phòng mở XML (. XLSX Excel 2007 trở lên
  • HTML
  • CSV
  • PDF*

Nhìn chung, PHPExcel cho phép bạn đọc, viết và tạo tài liệu Excel trong PHP. Nhược điểm duy nhất là đường cong học tập;

// 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

Làm cách nào để đọc tệp excel bằng PHPExcel?

Trong video này, tôi đã chỉ cho bạn cách đọc bất kỳ tệp excel nào bằng PHPExcel trong PHP. Vui lòng tải thư viện Lớp học. .
Cấu trúc dự án
index.php.

Read Excel By PHPExcel

đầu ra

Làm cách nào để đọc tệp xlsx trong PHP?

Làm cách nào để đọc tệp excel đã tải lên trong PHP?

php if(isset($_POST['SubmitButton'])){ //kiểm tra xem biểu mẫu đã được gửi hay chưa $target_dir = 'uploads/'; . tên cơ sở($_FILES["filepath"]["name"]); . '/Bao gồm/Lớp học/PHPExcel/IOFactory

Làm cách nào để kết nối excel với PHP?

Thiết lập kết nối . Để đóng kết nối, hãy sử dụng odbc_close hoặc odbc_close_all. $conn = odbc_connect("Nguồn CData ODBC Excel","người dùng","mật khẩu"); . Open the connection to Excel by calling the odbc_connect or odbc_pconnect methods. To close connections, use odbc_close or odbc_close_all. $conn = odbc_connect("CData ODBC Excel Source","user","password"); Connections opened with odbc_connect are closed when the script ends.