【问题标题】:How to import a csv file content into excel via python如何通过python将csv文件内容导入excel
【发布时间】:2019-08-27 14:13:05
【问题描述】:

我需要将 csv 文件的内容导入到已经创建且不会更改的 excel 工作表中(而 csv 的内容可以被覆盖)。

现在我正在使用 Excelwriter 通过 csv 阅读器创建一个 excel 文件

from pandas.io.excel import ExcelWriter

import pandas
csv_file = 'name.csv'


 ew = ExcelWriter('name.xlsx',sheet_name='name')
 pandas.read_csv(csv_file, decimal=',').to_excel(ew, sheet_name=csv_file)
 ew.save()

然后我可以将“ew”excel内容复制到另一个excel文件中,但是:

有没有办法直接读取 csv 文件而不是特定的工作簿选项卡?基本上是在特定选项卡中将 csv 文件导入到 excel 中。

谢谢!

【问题讨论】:

  • ExcelWriter 可用于写入现有工作表,并且您已经知道如何读取要添加的数据。

标签: python


【解决方案1】:

这是从import csv to xlsx python稍微编辑的

# First, import the .csv file
import pandas as pandas
df = pd.read_csv(my_filename)

# Now, open the book you are going to overwrrite
book = load_workbook(name.xlsx)
sheet_name = 'name'
# You specified both as name

# Assuming you are overwriting the same book...
with pd.ExcelWriter(name.xlsx, 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')

代码里面有注释。

【讨论】:

  • 没问题!如果这对您有帮助,请投票并接受作为答案,以便其他堆栈溢出用户可以参考! @GiacomoMureddu
猜你喜欢
  • 2015-03-31
  • 1970-01-01
  • 2012-10-07
  • 2013-07-27
  • 2021-11-21
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多