如何使用xlsxwriter迭代地编写数据而没有精确的行:列坐标?

时间:2016-05-12 09:57:09

标签: python csv xlsx xlsxwriter

我试图用xlsxwriter替换csv(我需要文档中某些行的样式功能),所以我试图在xlsxwriter中重新实现这个逻辑:

    with open('text.csv', 'wb') as file_csv:
        fieldnames = ["Date", "Advertiser", "Offer", "Affiliate", "Affiliate Source", "Impressions", "Clicks", "Cost click", "Conversions", "Cost", "Revenue", "Profit", "Real profit"]
        writer = csv.DictWriter(file_csv, delimiter=",", fieldnames=fieldnames)
        writer.writeheader()
        for d in data:
            real_profit = str(float(d['Stat']['profit']) - (int(d['Stat']['clicks']) * 0.0004))
            writer.writerow({"Date": d['Stat']['date'], "Advertiser": d['Advertiser']['company'], "Offer": d['Offer']['name'], "Affiliate": d['Affiliate']['company'], "Affiliate Source": d['Stat']['source'], "Impressions": d['Stat']['impressions'], "Clicks": d['Stat']['clicks'], "Cost click": str(int(d['Stat']['clicks']) * 0.0004), "Conversions": d['Stat']['conversions'], "Cost": d['Stat']['payout'], "Revenue": d['Stat']['revenue'], "Profit": d['Stat']['profit'], "Real profit": real_profit})
        totals = response['data']['totals']['Stat']
        writer.writerow({"Date": "Totals", "Impressions": totals['impressions'], "Clicks": totals['clicks'], "Conversions": totals['conversions'], "Cost": totals['payout'], "Revenue": totals['revenue'], "Profit": totals['profit']})

如何使用xlsxwriter迭代地在for循环中实现它,最后写入总行?

1 个答案:

答案 0 :(得分:3)

DictWriter只是从数组fieldnames中查找col号的一个包装器。你可以自己编写这样的包装器:

class DictWriter:
  def __init__(self, worksheet, fieldnames):
    self.worksheet =worksheet
    self.fieldnames = fieldnames
    self.nrow = 1

  def writerow(self, d):
    for k in d:
       ncol = self.fieldnames.index(k)
       self.worksheet.write(self.nrow, ncol, d[k])
    self.nrow += 1

  def writeheader(self):
    for ncol , fieldname in enumerate(self.fieldnames):
      self.worksheet.write(0, ncol, fieldname )

用法:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
fieldnames = [...]
writer = DictWriter(worksheet, fieldnames)
writer.writeheader()

# below comes your code 
for d in data:
  real_profit = str(float(d['Stat']['profit']) - (float(d['Stat']['clicks']) * 0.0004))
  writer.writerow({"Date": d['Stat']['date'], "Advertiser": d['Advertiser']['company'], "Offer": d['Offer']['name'], "Affiliate": d['Affiliate']['company'], "Affiliate Source": d['Stat']['source'], "Impressions": d['Stat']['impressions'], "Clicks": d['Stat']['clicks'], "Cost click": str(int(d['Stat']['clicks']) * 0.0004), "Conversions": d['Stat']['conversions'], "Cost": d['Stat']['payout'], "Revenue": d['Stat']['revenue'], "Profit": d['Stat']['profit'], "Real profit": real_profit})