When building a WordPress site, there are times when the data volume is simply too large to enter manually in the admin area. If the data already exists in Excel, importing it directly is often much more efficient. This article shows a straightforward way to upload an Excel file, read it with PHPExcel, convert it into an HTML table, and save that table into a custom field.
The example assumes that PHPExcel has already been installed and loaded in the project.
Step 1: upload the Excel file and save it as an attachment
The upload step is relatively simple. Many metabox libraries allow you to use a callback field for attachments, but you can also build the uploader directly with the WordPress Metabox API. The important part is saving the uploaded attachment ID into post meta.
$import_data = sanitize_text_field($_POST['wizhi_excel_import']);
update_post_meta($post_ID, 'wizhi_excel_import', $import_data);
Step 2: retrieve the saved custom field and generate the HTML table
After the attachment ID has been saved, read it back from post meta, resolve the actual file path with get_attached_file(), then load the spreadsheet with PHPExcel. Once the file is loaded, loop through the rows and build an HTML table string that can be saved back into another custom field.
$excel_id = get_post_meta($post_ID, 'wizhi_excel_import', true);
$excel_file = get_attached_file($excel_id);
$objPHPExcel = PHPExcel_IOFactory::load($excel_file);
$sheet = $objPHPExcel->getActiveSheet();
$html = '<table>';
foreach ($sheet->getRowIterator() as $row) {
$html .= '<tr>';
foreach ($row->getCellIterator() as $cell) {
$html .= '<td>' . $cell->getValue() . '</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
update_post_meta($post_ID, 'wizhi_excel_table', $html);
Summary and notes
In this example, the only requirement is to import spreadsheet data and convert it into an HTML table, so saving the generated table directly is a practical and simple choice. If you instead need to map Excel columns into post titles, post content, or other structured fields, you can add that logic during the conversion step.
The general workflow stays the same: upload the file, read the attachment, parse the spreadsheet, and store the processed result where your application needs it.
