简体   繁体   English

在Python中从csv编写xlsx文件

[英]writing xlsx file from csv in python

This is my code which loads the spreadsheet from doc excel file and creates a csvTranslations.csv, translations.py and translations.xlsx. 这是我的代码,该代码从doc Excel文件加载电子表格并创建了csvTranslations.csv,transitions.py和translations.xlsx。 The problem is it is creating a blank translattions.xlsx file and I don't know what am i doing wrong. 问题是它正在创建一个空白的translattions.xlsx文件,但我不知道我在做什么错。

import os
import random
import re
import csv
import requests
import io
import sys
import copy
import xlrd
import codecs
import time
import xlrd
from collections import OrderedDict
import simplejson as json
import xlsxwriter
from pandas.io.excel import ExcelWriter
import pandas
import openpyxl
from openpyxl import Workbook
from openpyxl.utils  import get_column_letter
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter

the function which will be called 将被调用的功能

def gen_translations():
    try:
        import xlrd
    except:
        print "Missing xlrd module!"
        return
    #return
    csv_file = 'translations.xlsx'
    if not os.path.exists(csv_file):
        print "Unable to update translations due to missing csv file!"
        return

    print "updating translations..."
    o = open("translations.py", "wb")

link to the google doc 链接到Google文档

url = "https://docs.google.com/spreadsheets/d/1g3nk_yzQxQFSxPN2lCvWwiHH8MgAqhpu5S763FRD_5I/gviz/tq?tqx=out:csv&sheet=translations"
    r = requests.get(url, verify=False)

    ow = io.open("csvTranslations.csv", "wb")

    ow.write(r.content)

    ow.close()



    try:
        print >> o, header
    except:
        print >> o, "#CANNOT PRINT HEADER:%s" % repr(header)

    with open("csvTranslations.csv", "rb") as csvfile:
        docreader = csv.reader(csvfile)
        headers = next(docreader)
        for row in docreader:
            decoded_row = [entry.decode("utf8") for entry in row]
            decoded_row[6] = translate(decoded_row[2], to_X)

            try:
                id = int(decoded_row[0])
            except:
                break
            keyword = decoded_row[1]
            languages = decoded_row[2:]
            '''
            try:
                print u" ; ".join(languages)
            except:
                print "#CANNOT PRINT:%s"%repr(languages)
            '''
            try:
                print >> o, "    %s = Word(%d, %s)" % (keyword, id, languages)
            except:
                print >> "ERROR: CANNOT PRINT %s = Word(%d,%s)" % (repr(keyword), id, repr(languages))
        try:
            print >> o, footer
        except:
            print >> o, "#ERROR CANNOT PRINT FOOTER:%s" % repr(footer)
        o.close()
        print "done!"

it seems that the problem is here because both csvTranslations and translations.py are being written but the translations.xlsx is not 似乎问题出在这里,因为同时编写了csvTranslations和translations.py,但不是translations.xlsx

        csv.register_dialect('colons', delimiter=',')

        reader = csv.reader(csvfile, dialect='colons')

        wb = Workbook()
        dest_filename = r"translations.xlsx"

        ws = wb.worksheets[0]

        for row_index, row in enumerate(reader):
            for column_index, cell in enumerate(row):
                column_letter = get_column_letter((column_index + 1))
                ws['%s%s'%(column_letter, (row_index + 1))].value = cell

        wb.save(filename=dest_filename)

It looks like you're trying to read "csvTranslations.csv" through twice, but you only open the file once. 您似乎要尝试通读两次“ csvTranslations.csv”,但您只打开了一次文件。 So, once your script has finished reading in order to write to translations.py, the file pointer to csvTranslations.csv is now located at the end of the file, and further attempts to read from csvfile return no data (instead, they indicate "you're already at the end of the file!", causing your loop at for row_index, row in enumerate(reader): to exit.) The easiest way to fix the problem would be to open csvTranslations.csv a second time, prior to the line reader = csv.reader(csvfile, dialect='colons') ; 因此,一旦脚本完成读取以写入translations.py的操作, 指向 csvTranslations.csv的文件指针现在位于文件的末尾,并且进一步尝试从csvfile读取的操作均不会返回任何数据(相反,它们表示“您已经在文件末尾了!”,导致在for row_index, row in enumerate(reader):处的循环出现,退出for row_index, row in enumerate(reader):中的行。)解决此问题的最简单方法是在第二次打开csvTranslations.csv之前到行reader = csv.reader(csvfile, dialect='colons') ; this gives you a new pointer into the file, this one back at the beginning. 这为您提供了一个指向文件的新指针,该指针从头开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM