Python 写入xlsx文件是一件痛苦的事情

Python 写入xlsx文件是一件痛苦的事情,python,excel,python-2.7,xlsxwriter,Python,Excel,Python 2.7,Xlsxwriter,我正试图使用xlsxwriter库在excel文件中写入一些数据,但我无法使其完美工作。我尝试了很多方法来写入正确的单元格,没有重复,但运气不佳 下面是我想做的屏幕截图: 我仍然得到的是: 我可以设置总额和收入权利的价值,但我不能设置收入和费用项下的账户价值,尽管我不知道如何防止这些重复 下面是我想添加的数据示例: [[{'account_type': u'sum', 'balance': -14112.2, 'company_id': 1, 'company_name':

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

下面是我想做的屏幕截图:

我仍然得到的是:

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

下面是我想添加的数据示例:

[[{'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

如果您在处理更复杂的问题时遇到困难,请简化它!这是一种经典的问题解决技术,在解决编程问题时也非常有用。你的问题似乎在于间隔,所以现在让我们做一个更简单的间隔:(顺便说一下,我想你忘了在收入项下提到200000产品销售,而你错误地将211000外汇损失列为两次):

以下是输出:

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

以下是输出:


解释:Excel可以很好地解释csv(逗号分隔值)文件。每个逗号都是行中项目之间的分隔符。换行符
“\n”
表示新行的开始。因此,当您看到
“、”、“
”时,excel将其解释为一行中的两个空单元格(请注意,此文本位于计算
公司标题字符串的逻辑中)。通过编辑代码中的
8
(如果希望这些列更靠近边缘,请将其设置为
7
6
),可以使公司列显示在一起。此任务无需使用
xlswritter
库。

如果您遇到更复杂的问题,请简化它!这是一种经典的问题解决技术,在解决编程问题时也非常有用。你的问题似乎在于间隔,所以现在让我们做一个更简单的间隔:(顺便说一下,我想你忘了在收入项下提到200000产品销售,而你错误地将211000外汇损失列为两次):

以下是输出:

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

以下是输出:


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

如果没有完整的工作示例,很难判断,但每次写入一行时,似乎都在增加各种
col\u spaceX
变量,而没有为新行重置它们。这可能就是为什么数据在工作表中越来越向右写入的原因。我一直在尝试它,但我无法让它正常工作,尽管如何管理重复数据?!如果没有一个完整的工作示例,很难说清楚,但是每次写一行时,似乎都在增加各种
col\u spaceX
变量,而没有为新行重置它们。这可能就是为什么数据在工作表中越来越向右写入的原因。我一直在尝试它,但我无法让它正常工作,尽管如何管理重复数据?!虽然不需要XlsxWriter,但我不认为使用
csv
更容易或更简单。jmcnamara的评论暗示OP的代码只需稍加修改即可工作。通过使用完全不同的库并重写整个程序,我认为这个答案实际上使事情变得比需要的复杂得多。虽然不需要XlsxWriter,但我不认为使用
csv
更容易或更简单。jmcnamara的评论暗示OP的代码只需稍加修改即可工作。通过使用一个完全不同的库并重写整个程序,我认为这个答案实际上使事情比需要的复杂得多。
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()
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()