简体   繁体   English

如何使用Python将CSV数据复制到现有的xlsx文件

[英]How to copy CSV data to an existing xlsx file using Python

I am using Python 3.4 and I am writing a short script. 我正在使用Python 3.4,并且正在编写一个简短的脚本。 I have an executable that take the output of a software and outputs a bunch of csv files with the requested data. 我有一个可执行文件,该可执行文件接受软件的输出,并输出一堆带有所需数据的csv文件。 I have created an Excel (xlsx) file as a template. 我已经创建了一个Excel(xlsx)文件作为模板。 It has a chart tailored to specific requirements. 它具有适合特定要求的图表。

I want to take a certain range of that data in each of those csv files and then input them into the existing excel template I have already created and save it with a unique file name. 我想在每个csv文件中获取一定范围的数据,然后将它们输入到我已经创建的现有excel模板中,并使用唯一的文件名进行保存。 Essentially iterate this process. 本质上是重复此过程。

Each csv file will have a unique name. 每个csv文件将具有唯一的名称。 My goal is to help automate creating graphs. 我的目标是帮助自动创建图形。 Sometimes this can end up being 100s of graphs. 有时,这最终可能是100个图形。 I have searched a lot on how to do this with little help. 我已经在很少的帮助下搜索了很多方法。

Again I would initiate the script and it would run through each csv file (whether there is 5 or 500) and then copy the data (a certain range which is always in the same cells) then paste it into the template xlsx file I have created and save it with a similar name to the csv except it will have .xlsx as the extension. 再次,我将启动脚本,它将遍历每个csv文件(无论是5还是500),然后复制数据(一定范围,始终在同一单元格中),然后将其粘贴到我创建的模板xlsx文件中并以与csv相似的名称保存它,但扩展名为.xlsx。

I do not know if this is the best approach or if I should create a csv template instead that it will copy to. 我不知道这是最好的方法,还是应该创建一个将复制到的csv模板。

Any help is much appreciated, thank you. 非常感谢您的任何帮助,谢谢。

1st approach 第一种方法

If your end goal is to generate graphs from data available in csv then you can use csvReader to read data and matplotlib to plot graphs. 如果最终目标是从csv中可用的数据生成图形,则可以使用csvReader读取数据,并使用matplotlib绘制图形。

Simple example: 简单的例子:

Sample csv file:
1,10,45
2,20,30
3,30,90
4,40,80

import csv
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

keys = ['Col1','Col2','Col3']
col1 = []
col2 = []
col3 = []
fd = open('sample.csv','r')
reader = csv.DictReader(fd,fieldnames=keys)
for row in reader:
    col1.append(int(row['Col1']))
    col2.append(int(row['Col2']))
    col3.append(int(row['Col3']))

pp = PdfPages("Sample.pdf")

plt.title("Col1 Vs Col2")
plt.xlabel("X-Values")
plt.ylabel("Y-Values")
plt.plot(col1,col2,label="Label 1",marker = "*")
legend = plt.legend(loc='best', shadow=True, fontsize=6)
legend.get_frame().set_facecolor('#00FFCC')
plt.grid(True)
plt.savefig(pp,format='pdf')
plt.clf()

plt.title("Col1 Vs Col3")
plt.xlabel("X-Values")
plt.ylabel("Y-Values")
plt.plot(col1,col3,label="Lable 2",marker = "*")
legend = plt.legend(loc='best', shadow=True, fontsize=6)
legend.get_frame().set_facecolor('#00FFCC')
plt.grid(True)
plt.savefig(pp,format='pdf')
plt.clf()
pp.close()

References: 参考文献:

2nd approach 第二种方法

You can use xlrd,xlwt and xlutils to perform operation on excel files 您可以使用xlrd,xlwt和xlutils对excel文件执行操作

Read data using csvReader, copy your existing template using xlutils, edit that and again save back 使用csvReader读取数据,使用xlutils复制现有模板,对其进行编辑,然后再次保存

Reference: 参考:

You can get all files by using the glob module: 您可以使用glob模块获取所有文件:

   import glob
   csv_file_list = glob.glob('*.csv')
   for fyle in csv_file_list:
       data = read_csv(fyle)
       write_to_excel(data)

Your read_csv() function should accept a CSV file and create an array of arrays (matrix) with the data. 您的read_csv()函数应接受CSV文件,并使用数据创建一个数组数组(矩阵)。 It's common to use the csv module (which in Python 3 doesn't require the unicodecsv 'add-on'). 通常使用csv模块(在Python 3中不需要unicodecsv'add-on')。

If the data is just numbers and you don't have to worry about quoted fields, then it's much faster to just read the rows. 如果数据只是数字,而您不必担心带引号的字段,那么读取行会更快。 So your read_csv() function would look like this: 因此,您的read_csv()函数将如下所示:

with open(fyle,'rb') as input:
    data = input.readlines().split(delim)
return data

Then your write_to_excel() function would accept 'data' and write to your template. 然后,您的write_to_excel()函数将接受“数据”并写入模板。

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

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