簡體   English   中英

如何使用python從mysql表數據中編寫excel

[英]How to write excel from mysql table data using python

我試圖通過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年所以要把上一年的價值結轉到那一年。

我不知道數據庫中的數據是什么。 如果你按照下面的例子,你可以

import xlwt


cols = [
    ['Feedstock', 'None', 'Naphtha', '5.00000', '2005', 'Y'],
    ['Feedstock', 'None', 'Naphtha', '0.00000', '2006', 'Y'],
    ['Feedstock', 'None', 'Naphtha', '0.00000', '2007', 'Y'],
    ['Building Blocks', 'Olefins', 'Ethylene', '5.00000', '2005', 'Y'],
    ['Building Blocks', 'Olefins', 'Ethylene', '5.00000', '2006', 'Y'],
]

res = {}
for c1, c2, c3, c4, c5, c6 in cols:
    res_key = "{}-{}-{}".format(c1, c2, c3)
    year_key = "{}-{}".format(c5, c6)
    years = {"year": year_key, "value": c4}
    res.setdefault(res_key, []).append(years)

title = ["" for _ in range(3)]
_lst = [title]
is_first = True
for info, years in res.items():
    rows = [item if not item == "None" else "" for item in info.split("-")]
    for item in years:
        year = item["year"]
        value = int(float(item["value"]))
        rows.append(value)
        if is_first:
            title.append(year)
    is_first = False
    _lst.append(rows)

book = xlwt.Workbook(encoding='utf8')
sheet = book.add_sheet('untitled', cell_overwrite_ok=True)

for row, rowdata in enumerate(_lst):
    for col, val in enumerate(rowdata):
        sheet.write(row, col, val)
book.save("test.xls")

我會創建excel表之前進行計算。 例如(如果表不是太大):

import pandas as pd
import numpy as np

# Load table into a DataFrame, see https://stackoverflow.com/questions/12047193
query = "select * from CPMAI"
result = cursor.execute(query)
df = pd.DataFrame(result.fetchall())
df.columns = result.keys()

pivot = df.pivot_table(values=["value"], index=["product"], columns=["year"], aggfunc=np.sum)

稍后,您可以循環遍歷樞軸元素並填充Excel工作表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM