写入xlsx文件令人痛苦

时间:2016-12-17 16:08:40

标签: python excel python-2.7 xlsxwriter

我尝试使用xlsxwriter库在excel文件中写入一些数据,但我无法完美地工作。我尝试了很多写入正确的单元格,没有重复,但没有运气。

以下是我想要做的屏幕截图:

What i want is HERE

我仍然得到的是:

What i achieved is HERE

我可以设置权利和收入的权利,但我不能在收入和费用下设置帐户的价值,尽管我不知道如何防止这些重复。

以下是我要添加的数据示例:

[[{'account_type': u'sum',
   'balance': -14112.2,
   'company_id': 1,
   'company_name': u'Company 1',
   'in_type': '',
   'level': 0,
   'name': u'Profit and Loss',
   'type': 'report'},
  {'account_type': u'account_type',
   'balance': 5887.78,
   'company_id': 1,
   'company_name': u'Company 1',
   'in_type': '',
   'level': 1,
   'name': u'Income',
   'type': 'report'},
  {'account_type': u'other',
   'balance': 5785.0,
   'company_id': 1,
   'company_name': u'Company 1',
   'in_type': u'Income',
   'level': 4,
   'name': u'200000 Product Sales',
   'type': 'account'},
  {'account_type': u'other',
   'balance': 102.78,
   'company_id': 1,
   'company_name': u'Company 1',
   'in_type': u'Income',
   'level': 4,
   'name': u'201000 Foreign Exchange Gain',
   'type': 'account'},
  {'account_type': u'account_type',
   'balance': -19999.98,
   'company_id': 1,
   'company_name': u'Company 1',
   'in_type': '',
   'level': 1,
   'name': u'Expense',
   'type': 'report'},
  {'account_type': u'other',
   'balance': -19999.98,
   'company_id': 1,
   'company_name': u'Company 1',
   'in_type': u'Expenses',
   'level': 4,
   'name': u'211000 Foreign Exchange Loss',
   'type': 'account'},
  {'balance': 0,
   'in_type': u'Income',
   'level': 4,
   'name': u'200 Product Sales'}],
 [{'account_type': u'sum',
   'balance': 5749.99,
   'company_id': 3,
   'company_name': u'Company 2',
   'in_type': '',
   'level': 0,
   'name': u'Profit and Loss',
   'type': 'report'},
  {'account_type': u'account_type',
   'balance': 5749.99,
   'company_id': 3,
   'company_name': u'Company 2',
   'in_type': '',
   'level': 1,
   'name': u'Income',
   'type': 'report'},
  {'account_type': u'other',
   'balance': 5749.99,
   'company_id': 3,
   'company_name': u'Company 2',
   'in_type': u'Income',
   'level': 4,
   'name': u'200 Product Sales',
   'type': 'account'},
  {'account_type': u'account_type',
   'balance': -0.0,
   'company_id': 3,
   'company_name': u'Company 2',
   'in_type': '',
   'level': 1,
   'name': u'Expense',
   'type': 'report'},
  {'balance': 0,
   'in_type': u'Income',
   'level': 4,
   'name': u'200000 Product Sales'},
  {'balance': 0,
   'in_type': u'Income',
   'level': 4,
   'name': u'201000 Foreign Exchange Gain'},
  {'balance': 0,
   'in_type': u'Expenses',
   'level': 4,
   'name': u'211000 Foreign Exchange Loss'}],
 [{'account_type': u'sum',
   'balance': -0.0,
   'company_id': 4,
   'company_name': u'Company 3',
   'in_type': '',
   'level': 0,
   'name': u'Profit and Loss',
   'type': 'report'},
  {'account_type': u'account_type',
   'balance': -0.0,
   'company_id': 4,
   'company_name': u'Company 3',
   'in_type': '',
   'level': 1,
   'name': u'Income',
   'type': 'report'},
  {'account_type': u'account_type',
   'balance': -0.0,
   'company_id': 4,
   'company_name': u'Company 3',
   'in_type': '',
   'level': 1,
   'name': u'Expense',
   'type': 'report'},
  {'balance': 0,
   'in_type': u'Income',
   'level': 4,
   'name': u'200 Product Sales'},
  {'balance': 0,
   'in_type': u'Income',
   'level': 4,
   'name': u'200000 Product Sales'},
  {'balance': 0,
   'in_type': u'Income',
   'level': 4,
   'name': u'201000 Foreign Exchange Gain'},
  {'balance': 0,
   'in_type': u'Expenses',
   'level': 4,
   'name': u'211000 Foreign Exchange Loss'}]]

这是我试过的python代码。希望我能找到一些帮助。

list_or = []
            col_space1_ = 8
            row_space1 = 6
            col_space2 = 8
            col_space3 = 8
            col_space4 = 8
            col_space5 = 8
            account_row = 12
            for record in lines:
                for sub_record in record:
                    if sub_record.get('in_type') == 'Income':
                        list_or.append(1)
            number_of_acc = len(list_or)/len(lines)
            income_co = ((number_of_acc * 2) + 2)
            income_lines = income_co + account_row
            income_lines1 = income_co + account_row
            worksheet.write(row_space1 + 2, 0, "Total", data_cell_format)
            worksheet.write(account_row, 1, "Income", data_cell_format)
            worksheet.write(income_lines, 1, "Expenses", data_cell_format)
            for line in lines:
                for sub_line in line:
                    if sub_line.get('account_type') == 'sum':
                        worksheet.write(row_space1, col_space1_, sub_line['company_name'], data_cell_format)
                        worksheet.write(row_space1 + 2, col_space1_, sub_line['balance'], data_cell_format)
                        col_space1_ = col_space1_ + 3

                    if sub_line.get('name') == 'Income':
                        worksheet.write(12, col_space2, sub_line['balance'], data_cell_format)
                        col_space2 = col_space2 + 3

                    if sub_line.get('name') == 'Expense':
                        worksheet.write(income_lines, col_space3, sub_line['balance'], data_cell_format)
                        col_space3 = col_space3 + 3

                    if sub_line.get('in_type') == 'Income':
                        worksheet.write(account_row, sub_line.get('level') - 2, sub_line['name'], data_cell_format)
                        worksheet.write(account_row, col_space4, sub_line['balance'], data_cell_format)
                        account_row = account_row + 2
                        col_space4 = col_space4 + 3

                    if sub_line.get('in_type') == 'Expenses':
                        worksheet.write(income_lines1, sub_line.get('level') - 2, sub_line['name'], data_cell_format)
                        worksheet.write(income_lines1, col_space5, sub_line['balance'], data_cell_format)
                        income_lines1 = income_lines1 + 2
                        col_space5 = col_space5 + 3

1 个答案:

答案 0 :(得分:5)

如果您遇到更复杂的问题,请更简单!这是一种经典的问题解决技术,它通常也可用于解决编程问题。你的问题似乎与间距有关,所以让我们暂时做一个更简单的间距:( PS,我认为你忘了在收入下提到200000产品销售,你错误地列出了两次以下的211000外汇损失):

rows = ["Profit and Loss",
        "Income",
        "201000 Foreign Exchange Gain",
        "200000 Product Sales",  # I think you forgot to mention this one
        "200 Product Sales",
        "Expense",
        "211000 Foreign Exchange Loss"]

# Next, sort each sublist in the order we desire
for sublist in lines:
    sublist.sort(key=lambda x: rows.index(str(x["name"])))

import numpy as np    
x = np.dstack((line for line in lines))

# Create file (Change this to your desired output path)
f = open("C:\Users\Matthew\Desktop\stack_simple_spacing.xls", 'w')

# Write out first row
companies = [item[0]["company_name"] for item in lines]
company_header_string = "".join("," + str(company) for company in companies)
f.write(company_header_string + "\n")

# Write out the rest of the rows (they're already sorted in the order desired)
for row in x[0]:
    output = row[0]["name"] + ","
    for item in row:
        output += str(item["balance"]) + ","
    f.write(output + "\n")

f.close()

这是输出:

simple spacing

如果你真的想要间距,你必须增加代码的复杂性,使其更难阅读/理解。但是修改我们现有的代码以简单地包含间距(而不是试图在一个shebang中完成所有操作)要容易得多:

rows = ["Profit and Loss",
        "Income",
        "201000 Foreign Exchange Gain",
        "200000 Product Sales", # I think you forgot to mention this one
        "200 Product Sales",
        "Expense",
        "211000 Foreign Exchange Loss"]

indents = [0, 1, 2, 2, 2, 1, 2]

# Next, sort each sublist in the order we desire
for sublist in lines:
    sublist.sort(key=lambda x: rows.index(str(x["name"])))

# Stack data so each tuple has data for a row
import numpy as np
x = np.dstack((line for line in lines))

# Create file (Change this to your desired output path)
f = open("C:\Users\Matthew\Desktop\stack_fancy_spacing.xls", 'w')

# Write out first row
companies = [item[0]["company_name"] for item in lines]
company_header_string = (","*8) + "".join(str(company) + ",,," for company in companies)
f.write(company_header_string + "\n")

# Write out the rest of the rows
for index, row in enumerate(x[0]):
    output = ","*indents[index] + row[0]["name"] + ","*(8 - indents[index])
    for item in row:
        output += str(item["balance"]) + ",,,"
    f.write(output + "\n")

f.close()

这是输出:

enter image description here

解释: Excel将完美地解释csv(逗号分隔值)文件。每个逗号都是行中项目之间的分隔符。换行符"\n"表示新行的开始。因此,当您看到",,,"时,excel会将其解释为一行中的两个空单元格(请注意,此文字位于计算company_header_string的逻辑中)。您可以通过编辑代码中的8使公司列显示在一起(如果您希望这些列更接近边缘,请将其设为76)。此任务不需要xlswritter库。