python将txt文件转换成xlsx,使用python将txt转换为xlsx时出错

My code is following.

import csv

import openpyxl

import sys

def convert(input_path, output_path):

"""

Read a csv file (with no quoting), and save its contents in an excel file.

"""

wb = openpyxl.Workbook()

ws = wb.worksheets[0]

with open(input_path) as f:

reader = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)

for row_index, row in enumerate(reader):

for col_index, value in enumerate(row):

ws.cell(row=row_index, column=col_index).value = value

wb.save(output_path)

def main():

try:

input_path, output_path = sys.argv[1:]

except ValueError:

print 'Usage: python %s input_path output_path' % (sys.argv[0],)

else:

convert(input_path, output_path)

if __name__ == '__main__':

main()

But I got this error.

Traceback (most recent call last):

File "txt2xlsx.py", line 33, in

main()

File "txt2xlsx.py", line 29, in main

convert(input_path, output_path)

File "txt2xlsx.py", line 18, in convert

ws.cell(row=row_index, column=col_index).value = value

File "C:\python27\lib\site-packages\openpyxl\worksheet\worksheet.py", line 350, in cell

column = get_column_letter(column)

File "C:\python27\lib\site-packages\openpyxl\utils\__init__.py", line 100, in get_column_letter

raise ValueError("Invalid column index {0}".format(idx))

ValueError: Invalid column index 0

I think I have installed openpyxl correctly.

And I remember I was using this program without any problem before. I recently bought a new computer so maybe this is a PC configuration issue.. But I can't figure out.

解决方案

Seems like you are using openpyxl 2.0.0 + ,according to changelog for Openpyxl 2.0.0 -

Cells are referenced with 1-indexing: A1 == cell(row=1, column=1)

The rows and columns index start at 1. So you should make your enumerate() function start at 1 as well. Example -

for row_index, row in enumerate(reader, 1):

for col_index, value in enumerate(row, 1):

ws.cell(row=row_index, column=col_index).value = value

Your particular code would work in openpyxl version less than 2.0.0 , it fails because of the above mentioned change in version 2.0.0 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值