【发布时间】:2019-04-08 08:13:51
【问题描述】:
我正在尝试通过 mysql 表数据在 Excel 表中插入数据。
'Feedstock', 'None', 'Naphtha', '5.00000', '2005', 'Y'
'Feedstock', 'None', 'Naphtha', '0.00000', '2006', 'Y'
'Feedstock', 'None', 'Naphtha', '0.00000', '2007', 'Y'
'Feedstock', 'None', 'Naphtha', '5.00000', '2008', 'Y'
'Feedstock', 'None', 'Naphtha', '5.00000', '2012', 'Y'
'Feedstock', 'None', 'Naphtha', '5.00000', '2014', 'Y'
'Feedstock', 'None', 'Naphtha', '5.00000', '2015', 'Y'
'Feedstock', 'None', 'Naphtha', '5.00000', '2016', 'Y'
'Feedstock', 'None', 'Naphtha', '5.00000', '2017', 'Y'
'Building Blocks', 'Olefins', 'Ethylene', '5.00000', '2005', 'Y'
'Building Blocks', 'Olefins', 'Ethylene', '5.00000', '2006', 'Y'
喜欢这个表格,想把这个数据填到excel表格里。
excel格式为:
2005-Y 2006-Y 2007-Y 2008-Y 2009-Y 2010-Y 2011-Y 2012-Y 2013-Y 2014-Y 2015-Y 2016-Y 2017-Y 2018-Y 2019-Y
Feedstock Naphtha 5 0 0 5 - - - 5 - 5 5 5 5 - -
Building Blocks (a)Olefine Ethylene 5 5 5 5 - - - 5 - 2.5 2.5 2.5 2.5 - -
Propylene 5 5 5 5 - - - 5 - 2.5 2.5 2.5 2.5 - -
Butadiene 5 5 5 5 - - - 5 - 2.5 2.5 2.5 2.5 - -
我试过了:
import pymysql
from xlsxwriter.workbook import Workbook
from openpyxl import load_workbook
import openpyxl
from openpyxl.styles import Alignment, Font
sqlconn = ".............."
cursor = sqlconn.cursor()
wb = load_workbook('cpm_auto.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
max_col = (sheet.max_column)
max_row = (sheet.max_row)
for row in range(3,max_row):
for col in range(4,max_col):
periods = sheet.cell(row = 1,column = col).value
period = periods.replace('-Y','')
val = sheet.cell(row = row,column = 3).value
if val == 'Naphtha':
query = "select Value from CPMAI where Product = '%s' and Year = '%s'" %(val,period)
result = cursor.execute(query)
if result > 0:
values = cursor.fetchone()
if len(values) > 0:
prev_value = values[0]
print(prev_value)
sheet.cell(row = row,column = col).value = values[0]
else:
sheet.cell(row=row, column=col).value = prev_value
break
wb.save('cpm_auto.xlsx')
我的代码: 我尝试了此代码,但此代码插入了具有值的年份的值,但我想插入 2005-2019 年的所有年份值。请参阅 excel 格式,2009、2010、2011、2013、2018、2019 年没有值所以想将上一年的值结转到那一年。
【问题讨论】:
-
您要做的是创建一个数据透视表。你玩过 panda 的 pivot 和 pivot_table 函数吗?
-
你能告诉我上面的例子是怎么做的吗
-
你的问题有点太宽泛了。您必须从 mysql 加载数据,参见例如pynative.com/python-mysql-select-query-to-fetch-data 然后你必须创建数据透视表,参见例如pandas.pydata.org/pandas-docs/stable/reference/api/…你应该试着写一些代码,这样我们可以帮助你
-
感谢 luca.vercelli。我用我的代码编辑了这个问题。我太接近了,但想将上一年的数据结转至 2019 年。