将字符串导出到Excel中的特定列

时间:2017-04-26 21:58:16

标签: python excel python-3.x

我想学习的是如何使第九列包含Z(相应下载文件的链接) 我没有得到任何错误,但它没有执行我想要它执行的。 任何帮助都非常感谢。

import csv; import glob; import os
from urllib.request import Request, urlopen
path = 'C:\\Users\\bruno.rojas\\Desktop\\Python_Data\\Test'; extension = 
'csv'; os.chdir(path)


file_name = 'TESTEXCEL'
# Creates empty lists that will hold their corresponding values
links = []
def WebGrab(url, filename):
    req = Request(url, headers={"User-Agent": "Mozilla/5.0"})
    webpage = urlopen(req).read()
    text_file = open(filename+'.csv', "wb")
    text_file.write(webpage)
    text_file.close()
    return text_file
with 
open('C:\\Users\\bruno.rojas\\Desktop\\Python_Data\\test\\'+file_name+'.csv') as f:
reader = csv.reader(f)
writer = csv.writer(f)
for row in reader:
    links.append("http://chart.finance.yahoo.com/table.csv?s="+row[0]+"&a="+row[3]+"&b="+row[4]+"&c="+row[2]+"&d="+row[7]+"&e="+row[8]+"&f="+row[6]+"&g=d&ignore=.csv")
    for z in links:
        WebGrab(z, row[0])
        for row in reader:
            row[9] = z

2 个答案:

答案 0 :(得分:1)

试试这个:

http://xlsxwriter.readthedocs.io/example_demo.html#ex-demo

以下示例:

##############################################################################
#
# A simple example of some of the features of the XlsxWriter Python module.
#
# Copyright 2013-2016, John McNamara, jmcnamara@cpan.org
#
import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

# Insert an image.
worksheet.insert_image('B5', 'logo.png')

workbook.close()

答案 1 :(得分:0)

我有更好的答案......

从这个页面:

http://openpyxl.readthedocs.io/en/default/usage.html

按顺序(下方)尝试这两个......

编写工作簿

>>> from openpyxl import Workbook
>>> from openpyxl.compat import range
>>> from openpyxl.utils import get_column_letter
>>>
>>> wb = Workbook()
>>>
>>> dest_filename = 'empty_book.xlsx'
>>>
>>> ws1 = wb.active
>>> ws1.title = "range names"
>>>
>>> for row in range(1, 40):
...     ws1.append(range(600))
>>>
>>> ws2 = wb.create_sheet(title="Pi")
>>>
>>> ws2['F5'] = 3.14
>>>
>>> ws3 = wb.create_sheet(title="Data")
>>> for row in range(10, 20):
...     for col in range(27, 54):
...         _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
>>> print(ws3['AA10'].value)
AA
>>> wb.save(filename = dest_filename)

阅读现有工作簿

>>> from openpyxl import load_workbook
>>> wb = load_workbook(filename = 'empty_book.xlsx')
>>> sheet_ranges = wb['range names']
>>> print(sheet_ranges['D18'].value)
3

完全为我工作!

Σ8•d