将csv文件转换为xlsx

时间:2014-05-12 15:19:53

标签: excel python-2.7 csv python-3.x

我试图创建一些脚本,当它被调用时会自动将csv文件转换为xlsx文件。我正在尝试使用python脚本。我有分隔符的问题,因为我需要放两个分隔符:tab和逗号

import os
import glob
import csv
from xlsxwriter.workbook import Workbook

files = ['test3.csv']

for i in files:
    workbook = Workbook(i + '.xlsx')
    worksheet = workbook.add_worksheet()
with open('test3.csv') as f:
        reader=csv.reader((f), delimiter=",")
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
workbook.close()

这段代码没问题,但是我需要在内部分隔符中设置条件" \ t" ? 有谁知道怎么做?

2 个答案:

答案 0 :(得分:3)

作者是Excel2007而不是XLSX,因此您传递给createWriter的值告诉它您想要使用哪个Writer;和OfficeOpenXML格式文件没有分隔符或附件,因此在Excel2007 Writer中没有用于设置这些文件的Writer方法

require_once 'PHPExcel/PHPExcel/IOFactory.php';
$csv = PHPExcel_IOFactory::load("test.csv");
$writer= PHPExcel_IOFactory::createWriter($csv, 'Excel2007');
$writer->save("test.xlsx");

答案 1 :(得分:0)

您可以使用this,也许可以提供帮助

<?php 
/** 
 * CSVToExcelConverter 
 */ 
class CSVToExcelConverter 
{ 
    /** 
     * Read given csv file and write all rows to given xls file 
     *  
     * @param string $csv_file Resource path of the csv file 
     * @param string $xls_file Resource path of the excel file 
     * @param string $csv_enc Encoding of the csv file, use utf8 if null 
     * @throws Exception 
     */ 
    public static function convert($csv_file, $xls_file, $csv_enc=null) { 
        //set cache 
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp; 
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod); 

        //open csv file 
        $objReader = new PHPExcel_Reader_CSV(); 
        if ($csv_enc != null) 
            $objReader->setInputEncoding($csv_enc); 
        $objPHPExcel = $objReader->load($csv_file); 
        $in_sheet = $objPHPExcel->getActiveSheet(); 

        //open excel file 
        $objPHPExcel = new PHPExcel(); 
        $out_sheet = $objPHPExcel->getActiveSheet(); 

        //row index start from 1 
        $row_index = 0; 
        foreach ($in_sheet->getRowIterator() as $row) { 
            $row_index++; 
            $cellIterator = $row->getCellIterator(); 
            $cellIterator->setIterateOnlyExistingCells(false); 

            //column index start from 0 
            $column_index = -1; 
            foreach ($cellIterator as $cell) { 
                // put up your delimiter or cell formatting here
                $column_index++; 
                $out_sheet->setCellValueByColumnAndRow($column_index, $row_index, $cell->getValue()); 
            } 
        } 

        //write excel file 
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
        $objWriter->save($xls_file); 
    } 
}

以下是您可以使用它的方法:

<?php 
if (!isset($_FILES["file"])) 
{ 
?> 
<html> 
    <body> 
        <h1>Convert CSV to XLSX</h1> 
        <form action="test.php" method="post" enctype="multipart/form-data"> 
            <input type="file" name="file"/> 
            <input type="submit"/> 
        </form> 
    </body> 
</html> 
<?php 
    exit; 
} 

//obtain PHPExcel from http://phpexcel.codeplex.com 
require_once('PHPExcel.php'); 
require_once('CSVToExcelConverter.php'); 

if ($_FILES["file"]["error"] > 0) 
{ 
    echo "Error: " . $_FILES["file"]["error"]; 
    exit; 
} 

try 
{ 
    header('Content-type: application/ms-excel'); 
    header('Content-Disposition: attachment; filename='.'test.xlsx'); 

    CSVToExcelConverter::convert($_FILES['file']['tmp_name'], 'php://output'); 
} catch(Exception $e) { 
    echo $e->getMessage(); 
}