我将.xlsx文件转换为.csv时遇到问题。当我尝试转换它时,csv文件出现并激活了Text Wrap。问题是,我需要将csv文件导入数据库,当前格式不允许我这样做。我有问题,如何在保存csv文件时禁用文本换行,或在将文件导入数据库时忽略文本换行?
转换:
require_once 'Classes/PHPExcel.php'; // (this should include the autoloader)
require_once 'Classes/PHPExcel/IOFactory.php';
$excel_readers = array(
'Excel5' ,
'Excel2003XML' ,
'Excel2007'
);
$reader = PHPExcel_IOFactory::createReader('Excel2007');
$reader->setReadDataOnly(true);
$path = 'temp.xlsx';
$excel = $reader->load($path);
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(',');
$writer->save('temp.csv');
导入数据库:
if (file_exists('temp.csv')) {
$i=0;
require "connection.php";
$handle = fopen("temp.csv", "r");
$import=$db->prepare("INSERT INTO adherence(
dateandtime,
lastname,
firstname,
paidtime,
approvedtime,
notadhering) VALUES(
?,?,?,?,?,?)");
while (($data = fgetcsv($handle, 1000, ',', "'")) !== FALSE) {
if($i>0) {
$data = str_replace('"', '', $data);
$myDate = date("Y/m/d",strtotime(str_replace('/','-',$data[0])));
$import->bindParam(1, $myDate, PDO::PARAM_STR);
$import->bindParam(2, $data[1], PDO::PARAM_STR);
$import->bindParam(3, $data[2], PDO::PARAM_STR);
$import->bindParam(4, $data[3], PDO::PARAM_STR);
$import->bindParam(5, $data[4], PDO::PARAM_STR);
$import->bindParam(6, $data[5], PDO::PARAM_STR);
$import->execute();
}
$i++;
}
$removal=$db->prepare("delete FROM adherence WHERE approvedtime = '0' OR notadhering IS NULL");
$removal->execute();
fclose($handle);
echo 'IMPORTED' ;
}
任何帮助将不胜感激!
答案 0 :(得分:1)
我怀疑它"包装文字"这导致了问题,但是细胞中出现了新的行字符。 PHPExcel没有提供任何自动删除它们的方法。最好的选择是迭代单元格,用空格替换所有出现的"\n"
。
修改强>
像
这样的东西foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getColumnIterator() as $column) {
$cellIterator = $column->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
// Convert any rich text cells to plain text
if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_INLINE) {
$cell->setValueExplicit($cell->getValue()->getPlainText());
}
// Remove any newline characters in string cells
if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING) {
$cell->setValue(str_replace("\n", " ", $cell->getValue()));
}
}
}
}
可能有帮助