Skip to content

Instantly share code, notes, and snippets.

@danielrw7
Last active June 13, 2017 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielrw7/e1e954718fbb42a50215237738acc70b to your computer and use it in GitHub Desktop.
Save danielrw7/e1e954718fbb42a50215237738acc70b to your computer and use it in GitHub Desktop.
<?php
function convert_spreadsheet_rows_to_sql($table_name, $row_mappings = array(), $rows = array(), $start_row = 2) {
$mappings = array();
$fields = array();
foreach ($row_mappings as $ind => $field) {
if ($field) {
$mappings[] = $ind;
$fields[] = $field;
}
}
$fields_sql = "`" . implode("`, `", $fields) . "`";
$insert_rows = "";
$num_rows = count($rows);
for ($i = $start_row-1; $i < $num_rows; $i++) {
$row = $rows[$i];
$row_fields = array();
foreach ($mappings as $mapping) {
$row_fields[] = addslashes(trim($row[$mapping]));
}
if ($insert_rows) $insert_rows .= ",\n";
$insert_rows .= "('" . implode("', '", $row_fields) . "')";
}
return <<<SQL
INSERT INTO `$table_name`
($fields_sql) VALUES
$insert_rows
SQL;
}
function get_spreadsheet_type($filename) {
$path = pathinfo($filename);
$type = $path["extension"];
if ($type == "csv") {
return $type;
}
return $type == "xlsx" ? "Excel2007" : "Excel5";
}
function get_spreadsheet_rows($filename, $type = "", $worksheet_key = "") {
if (!$type) {
$type = get_spreadsheet_type($filename);
}
if ($type == "csv") {
$fh = fopen($filename, "r");
$rows = array();
while ($row = fgetcsv($fh)) {
$rows[] = $row;
}
return $rows;
}
$reader = PHPExcel_IOFactory::createReader($type);
$loaded = $reader->load($filename);
foreach ($loaded->getWorksheetIterator() as $worksheet) {
$worksheets[$worksheet->getTitle()] = $worksheet->toArray();
}
return $worksheet_key ? $worksheets[$worksheet_key] : $worksheets;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment