excel数据读取和拆分与PHP

时间:2013-10-13 09:30:21

标签: php excel

我有一个excel文件,其中包含第一栏中的hundres电子邮件..

就像这样,

Ameerali Uncle. <seenameer@gmail.com>
Afkaar (Habeeb). <afkar.mam@gmail.com>
Ameerali Uncle. <seenameer@gmail.com>

我想从&lt;&gt;中取消这个签名并将其放入新列并保留第一列的名称。所以在这之后,它就像

column 1         column 2
Afkaar (Habeeb)  afkar.mam@gmail.com

这可能与php有关吗?有人可以建议我这样做的好机制。

感谢

编辑1

我的示例excel文件如下所示。

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以使用PHPExcel库从excel文件读取/写入。 (下载和文档可在http://phpexcel.codeplex.com/获得)。然后使用RegExs分隔字符串。

编辑1

代码将是这样的:

//  Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';

$inputFileName = './example1.xlsx';
$outputFileName = './output.xlsx';

//  Read your Excel workbook
try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);

    $outputObj = new PHPExcel();
} catch(Exception $e) {
    die('Error loading file: '. $e->getMessage());
}

//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();

$outputObj->setActiveSheetIndex(0);
$outSheet = $outputObj->getActiveSheet();

//  Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++){ // As row 1 seems to be header
    //  Read cell A2, A3, etc.
    $line = $sheet->getCell('A' . $row)->getValue();
    preg_match("|([^\.]+)\. <([^>]+)>|", $line, $data);
    // $data[1] will be name & $data[2] will be email
    $outSheet->setCellValue('A' . $row, $data[1]);
    $outSheet->setCellValue('B' . $row, $data[2]);
}

// write new data into a .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($outputObj);
$objWriter->save($outputFileName);

来源:Stackoverflow QuestionPHPExcel Example