【问题标题】:Converting csv file to xlsx将csv文件转换为xlsx
【发布时间】:2014-05-12 15:19:53
【问题描述】:

我正在尝试制作一些脚本,当它被调用时会自动将 csv 文件转换为 xlsx 文件。我正在尝试使用python脚本。我对分隔符没有什么问题,因为我需要放置两个分隔符:制表符和逗号

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" 吗? 有人知道怎么做吗?

【问题讨论】:

  • 您在 Python 中尝试了什么,为什么没有成功?同样,你的 php 脚本不工作怎么办?
  • 看看xlswriter tag
  • Exel 将打开 CSV 文件,您的初始 CSV 格式是否错误(听起来可能不是 CSV)并且您正在尝试将其转换为制表符分隔?
  • 令人难以置信的是,一个问题如何在一个月的时间内完全从使用 PHP 代码的问题变为使用 Python 代码的问题

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


【解决方案1】:

Writer 是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");

【讨论】:

  • 谢谢,我试试这个:)
【解决方案2】:

你可以使用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(); 
}

【讨论】:

  • 我看到了这个解决方案,但他会按照我的意愿格式化我的 csv 吗?我可以在哪里放置我想要的分隔符?
  • 查看代码$column_index = -1; foreach ($cellIterator as $cell) { $column_index++; $out_sheet-&gt;setCellValueByColumnAndRow($column_index, $row_index, $cell-&gt;getValue()); } ,您可以在其中放置分隔符