This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Cómo crear y editar hojas de cálculo Excel en PHP

Updated on July 18, 2025

3 Min Read

PHP está altamente enriquecido con características de un buen lenguaje de scripting. Proporciona numerosas bibliotecas para fines específicos. PHP proporciona una biblioteca para tratar archivos Excel. Se llama biblioteca PHP Excel. Te permite leer y escribir hojas de cálculo en varios formatos, como csv, xls, ods y xlsx. Necesitarás asegurarte de que tienes la versión actualizada de PHP no anterior a PHP 5.2 . Además, deberás tener instaladas las extensiones php_qd2, php_xml y php_zip.

También te puede gustar: Cómo alojar PHP en DigitalOcean

La creación de hojas de cálculo es un caso de uso muy común en el desarrollo PHP. Se utiliza para exportar datos a una hoja de cálculo Excel. A continuación se muestra el código para crear una hoja de cálculo Excel utilizando la biblioteca PHP Excel.

Código:

//Including PHPExcel library and creation of its object

require('PHPExcel.php');

$phpExcel = new PHPExcel;

// Setting font to Arial Black

$phpExcel->getDefaultStyle()->getFont()->setName('Arial Black');

// Setting font size to 14

$phpExcel->getDefaultStyle()->getFont()->setSize(14);

//Setting description, creator and title

$phpExcel ->getProperties()->setTitle("Vendor list");

$phpExcel ->getProperties()->setCreator("Robert");

$phpExcel ->getProperties()->setDescription("Excel SpreadSheet in PHP");

// Creating PHPExcel spreadsheet writer object

// We will create xlsx file (Excel 2007 and above)

$writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007");

// When creating the writer object, the first sheet is also created

// We will get the already created sheet

$sheet = $phpExcel ->getActiveSheet();

// Setting title of the sheet

$sheet->setTitle('My product list');

// Creating spreadsheet header

$sheet ->getCell('A1')->setValue('Vendor');

$sheet ->getCell('B1')->setValue('Amount');

$sheet ->getCell('C1')->setValue('Cost');

// Making headers text bold and larger

$sheet->getStyle('A1:D1')->getFont()->setBold(true)->setSize(14);

// Insert product data

// Autosize the columns

$sheet->getColumnDimension('A')->setAutoSize(true);

$sheet->getColumnDimension('B')->setAutoSize(true);

$sheet->getColumnDimension('C')->setAutoSize(true);

// Save the spreadsheet

$writer->save('products.xlsx');

Deja de perder el tiempo con los servidores

Cloudways se encarga de gestionar los servidores por ti para que puedas centrarte en crear grandes aplicaciones y mantener contentos a tus clientes.

Enfoque alternativo:

Alternativamente, se puede descargar la hoja de cálculo en lugar de guardarla en el servidor. Puedes utilizar el siguiente código:

header('Content-Type: application/vnd.ms-excel');

header('Content-Disposition: attachment;filename="file.xlsx"');

header('Cache-Control: max-age=0');

$writer->save('php://output');

¿Cómo editar una hoja de cálculo existente en PHP?

El proceso de edición es bastante similar al proceso de creación de hojas de cálculo. Utiliza el siguiente código para hacerlo:

// Include PHPExcel library and create its object

require('PHPExcel.php');

// Load an existing spreadsheet

$phpExcel = PHPExcel_IOFactory::load('products.xlsx');

// Get the first sheet

$sheet = $phpExcel ->getActiveSheet();

// Remove 2 rows starting from the row 2

$sheet ->removeRow(2,2);

// Insert one new row before row 2

$sheet->insertNewRowBefore(2, 1);

// Create the PHPExcel spreadsheet writer object

// We will create xlsx file (Excel 2007 and above)

$writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007");

// Save the spreadsheet

$writer->save('products.xlsx');

También te puede gustar: Cómo importar y exportar archivos CSV con PHP y MySQL

¿Cómo preparar hojas de cálculo para imprimirlas?

Para preparar una hoja de cálculo, debes establecer el tamaño, los márgenes y la orientación del papel.

$sheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);

$sheet -> getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);

$sheet->getPageMargins()->setTop(1);

$sheet ->getPageMargins()->setRight(0.75);

$sheet ->getPageMargins()->setLeft(0.75);

$sheet ->getPageMargins()->setBottom(1);

Aloja sitios web PHP con facilidad [A partir de 10 $ de crédito].

  • Puesta en escena gratuita
  • Copia de seguridad gratuita
  • PHP 8.0
  • Sitios web ilimitados

PRUEBA AHORA

Conclusión

La biblioteca PHPExcel es muy útil para realizar cálculos y gráficos. A menudo se utiliza para almacenar datos en hojas Excel o para importar datos de hojas Excel a través de un sitio web PHP. ¿Tienes alguna pregunta sobre lo que hemos hablado? ¡Deja un comentario y te responderé!

Además de conocer trucos como trabajar con hojas de cálculo en PHP, cualquier desarrollador PHP inteligente conoce la importancia de una excelente solución de alojamiento para las aplicaciones web que crea. La Plataforma de Alojamiento PHP Gestionado de Cloudways te ofrece un rendimiento ultrarrápido gracias a su pila de alojamiento optimizada. Inicia hoy mismo tu prueba gratuita para aventurarte en el futuro del alojamiento PHP.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Start Growing with Cloudways Today.

Our Clients Love us because we never compromise on these

Shahzeb Ahmed

Un creativo de día (con una taza de té) y un creativo de noche. Ahmad Kamran es redactor de contenidos estacionales y Ejecutivo de Marketing Senior en Cloudways. Puedes encontrarle en su escritorio escribiendo, elaborando estrategias o jugando. Y en caso de que no puedas encontrarle aquí, estará en la montaña o junto a la orilla del río.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Iniciar mi recorrido