phpexcel如何读和写大于26列的excel
主要运用到PHPExcel_Cell类的两个方法
1读取excel大于26列时.
- PHPExcel_Cell::columnIndexFromString($highestColumm)://由列名转化为列索引数字 'A->0,Z->25'
1>计算出总列数
- $highestColumm = $sheet->getHighestColumn(); // 获得最多的列数,返回列名的大写字母 如 'AB','F'等
- $end_index = PHPExcel_Cell::columnIndexFromString($highestColumm);//由列名转为列数('AB'->28)
- $PHPExcel = $reader->load($file_path_root . '/' . $file_name);//文件路径加载文件名
- $sheet = $PHPExcel->getSheet(0);
- $highestRow = $sheet->getHighestRow(); // 取得总行数
- $highestColumm = $sheet->getHighestColumn(); // 取得总列数
- $end_index = PHPExcel_Cell::columnIndexFromString($highestColumm);//由列名转为列数('AB'->28)
- $titles = array();
- $content = array();
- /** 循环读取每个单元格的数据 */
- for ($row = 1; $row <= $highestRow; $row++) {
- for ($column = 0; $column < $end_index; $column++) {
- $col_name = PHPExcel_Cell::stringFromColumnIndex($column);//由列数反转列名(0->'A')
- $value = mb_convert_encoding($sheet->getCell($col_name . $row)->getValue(), 'gbk', 'utf8');//转码
- if ($row == 1) {
- //获取表头
- $titles[] = preg_replace('/\s/', '', $value);
- } else {
- if ($sheet->getCell($col_name . $row)->getDataType() == PHPExcel_Cell_DataType::TYPE_NUMERIC) {
- //数字类型时,三位精度标准来比较该数是否在0,1之间,转换为百分数,保留一位小数
- if (bccomp(floatval($value), floatval('1'), 3) == -1 && bccomp(floatval($value), floatval('0'), 3) == 1) {
- $value = sprintf("%01.1f", $value * 100) . '%';
- }
- }
- $content[$row][$column] = preg_replace('/\s/', '', $value);
- }
- }
- }
上传excel时,如果没有读写权限,可以写到tmp目录下,这个目录下一般都是有读写权限的.
2写大于26列的excel
- $title_col = PHPExcel_Cell::stringFromColumnIndex($k);//标题行列名,由列索引反转列名(0->'A')
- </pre><pre name="code" class="php"><pre name="code" class="php">foreach($titles as $k =>$t)
- {
- $title_col = PHPExcel_Cell::stringFromColumnIndex($k);//标题行列名,由列索引反转列名(0->'A')
- $this->_objPHPExcel->getActiveSheet()->getColumnDimension($title_col)->setWidth(12);
- $this->_objPHPExcel->setActiveSheetIndex()->getStyle($title_col."1")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
- $this->_objPHPExcel->getActiveSheet()->setCellValue($title_col."1",iconv('GBK','UTF-8//IGNORE',$t));//标题行
- }
3读取excel百分号时自动转化为了小数
处理单元格数据时,如果有百分号小数会自动转为小数,处理时需要判断单元格数据类型,因为初步认定只有百分数是小数,其余各列不存在小数.故处理结果:
判断数据类型为数字,其余几种类型都在 PHPExcel_Cell_DataType类中:
- /* Data types */
- const TYPE_STRING2 = 'str';
- const TYPE_STRING = 's';
- const TYPE_FORMULA = 'f';
- const TYPE_NUMERIC = 'n';
- const TYPE_BOOL = 'b';
- const TYPE_NULL = 'null';
- const TYPE_INLINE = 'inlineStr';
- const TYPE_ERROR = 'e';
- if ($sheet->getCell($col_name . $row)->getDataType() == PHPExcel_Cell_DataType::TYPE_NUMERIC) {
- //数字类型时,三位精度标准来比较该数是否在0,1之间,转换为百分数,保留一位小数
- if (bccomp(floatval($value), floatval('1'), 3) == -1 && bccomp(floatval($value), floatval('0'), 3) == 1) {
- $value = sprintf("%01.1f", $value * 100) . '%';
- }
- }
判断浮点数是否在0-1之间(三位精度),然后组合成百分数即可:
- $value = sprintf("%01.1f", $value * 100) . '%';