将csv导入xlsx python

时间:2017-07-11 08:09:05

标签: python excel csv

我试图将csv文件中的一些数据存入excel文件。 我存在的excel文件包含图像,xlrd无法获取图像。 我尝试使用xlsxwriter,但它不能附加到现有的xslx。 我发现的唯一解决方案是使用openpyxl。

import openpyxl
xfile = openpyxl.load_workbook('my_exist_file')
sheet = xfile.get_sheet_by_name('Sheet1')
with open("my_csv", 'rb') as f:
    reader = csv.reader(f)
    for r, row in enumerate(reader):
        for c, col in enumerate(row):
           -here is my problem- 

如何将csv数据(即表格)写入现有xslx中的特定位置?我想我的桌子将从K2格开始。

谢谢!

2 个答案:

答案 0 :(得分:0)

使用工作表的单元格方法更新特定单元格

sheet.cell(row=<row>, column=<col>, value=<val>)

在加载工作簿时使用keep_vba=True通常是个好主意。查看the help page了解详情。

同时检查answer to这个问题。

答案 1 :(得分:0)

读取CSV

使用pandas.read_csv提取信息

import pandas as pd
df = pd.read_csv(my_filename)

您可能需要指定的选项

  • sep:使用哪个分隔符
  • 编码
  • header:第一行是一行标签吗?
  • index_col:是第一列索引

添加到Excel工作表

受到启发:https://stackoverflow.com/a/20221655/1562285 查看pandas.to_excel文档以了解其他可能的选项

book = load_workbook(old_filename)
sheet_name = 'Sheet1'
with pd.ExcelWriter(new_filename, engine='openpyxl')  as writer:

    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

    df.to_excel(writer, sheet_name=sheet_name, startrow=1, startcol=10, engine='openpyxl')

startrow和startcol说明要在工作表中粘贴数据的位置。

此方法可能会覆盖此工作表上的先前内容。如果是这样,您将必须遍历DataFrame的列和行,并将它们半手动添加到工作表中

插入图像

如果要在外部插入图像,可以使用documentation

中的代码
    from openpyxl.drawing.image import Image
    ws = book['sheet_name_for_images']
    ws['A1'] = 'You should see three logos below'
    img = Image('logo.png')

    # add to worksheet and anchor next to cells
    ws.add_image(img, 'A1')

我没有对此进行测试,您可能需要在writer.sheets = ...

之前插入此代码
相关问题