我正在尝试使用 php 脚本读取 xlsx 文件,并将信息从单元格传递到 MYSQL
这是我的代码,我使用的是 PHPExcel 1.7.6 版和 PHP 5.3.5
require_once 'PHPExcel.php';
$inputFileType = 'Excel2007';
$inputFileName = $upload_path . $filename;
/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
class chunkReadFilter implements PHPExcel_Reader_IReadFilter
{
private $_startRow = 0;
private $_endRow = 0;
/** Set the list of rows that we want to read */
public function setRows($startRow, $chunkSize) {
$this->_startRow = $startRow;
$this->_endRow = $startRow + $chunkSize;
}
public function readCell($column, $row, $worksheetName = '') {
// Only read the heading row, and the configured rows
if (($row == 1) ||
($row >= $this->_startRow && $row < $this->_endRow)) {
return true;
}
return false;
}
}
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Define how many rows we want to read for each "chunk" **/
$chunkSize = 2048;
/** Create a new Instance of our Read Filter **/
$chunkFilter = new chunkReadFilter();
/** Tell the Reader that we want to use the Read Filter **/
$objReader->setReadFilter($chunkFilter);
/** Loop to read our worksheet in "chunk size" blocks **/
for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) {
/** Tell the Read Filter which rows we want this iteration **/
$chunkFilter->setRows($startRow,$chunkSize);
/** Load only the rows that match our filter **/
$objPHPExcel = $objReader->load($inputFileName);
// Need to pass the cell values into the variables
这是我需要使用类似的东西的地方
for ($x = 2; $x < = count($data->sheets[0]["cells"]); $x++) {
$item_number = $data->sheets[0]["cells"][$x][1];
$qty_sold = $data->sheets[0]["cells"][$x][2];
$cost_home = $data->sheets[0]["cells"][$x][3];
这适用于 phpexcelreader,但我只是不知道哪些函数适用于 phpExcel
//here is where I would pass those values into MYSQL
$sql = "INSERT INTO sales_report (`item_number`,`qty_sold`, `cost_home`)
VALUES ('$item_number',$qty_sold,'$cost_home')";
echo $sql."\n";
mysql_query($sql);
}
?>
我完全不知道如何将电子表格中的数据导入 mysql
编辑:
我已经设法使用以下数组打印数据
foreach ($objWorksheet->getRowIterator() as $row) {
$j = 1;
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$data->sheets[0]['cells'][$i][$j] = $cell->getValue();
$j++;
} // end cell getter
$i++;
} // end row getter
但我似乎无法将其插入到我的表中。我也尝试过使用 implode 函数,但没有任何反应。
最佳答案
执行此操作的最简单方法是即时将 xlsx 转换为 csv 文件,而不是使用正常的 CSV 解析。只需实例化 CSVWriter 并保存到一个临时位置(明天我可以提供示例代码)
示例代码:
$objReader = PHPExcel_IOFactory::load ( $file_path );
$writer = PHPExcel_IOFactory::createWriter ( $objReader, 'CSV' );
$writer->save ( $csv_path );
if (($handle = fopen ( $csv_path, "r" )) !== false) {
while ( ($data = fgetcsv ( $handle)) !== false ) {
print_r($data);
}
}
关于PHPExcel - 读取单元格并将其传递到 MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8042698/