将xlsx文件转换为二进制数据

时间:2017-12-27 13:59:40

标签: python excel

我正在创建xlsx文件,我差不多完成因为我成功创建了文件,但我想要做的是将当前创建的文件添加到数据库表中,我的列需要bytea数据,所以我需要以二进制数据转换文件。我在最后一行尝试了但它给了我错误AttributeError: 'Workbook' object has no attribute 'read'。下面是我正在使用的函数代码/

    file_name = 'test'
    workbook = xlsxwriter.Workbook(file_name)
    bold = workbook.add_format({'bold': True})  # Add a bold format to use to highlight cells.
    row_count = 2
    for customer in customers:
        customer_orders = self.env['amgl.order_line'].search([('customer_id', '=', customer.id)])
        column_count = 0
        for customer_order in customer_orders:
            worksheet.write(row_count, column_count, 'GST_Customer_account_number')
            column_count += 1
            worksheet.write(row_count, column_count, customer.full_name)
            column_count += 1
            worksheet.write(row_count, column_count, customer.account_number)
            column_count += 1
            worksheet.write(row_count, column_count, customer_order.create_date)
            column_count += 1
            worksheet.write(row_count, column_count, 'PR')
            column_count += 1
            worksheet.write(row_count, column_count, customer_order.products.product_code)
            column_count += 1
            worksheet.write(row_count, column_count, customer_order.quantity)
            column_count += 1
            worksheet.write(row_count, column_count, 'amark')
            column_count += 1
            worksheet.write(row_count, column_count, 'amark_customer_code')
            column_count += 1
            worksheet.write(row_count, column_count, 'Descripion')
            column_count += 1
            worksheet.write(row_count, column_count, 'transaction_number')
            row_count += 1

    workbook.close()
    data = 0
    base64.encode(workbook, data)

更新 我试图做以下操作并使其编码。但是现在我面临的问题是每当我发送该记录作为附件时。该文件显示二进制文件而非实际文本。

这是我试过的。

byte_data = 0
    with open(file_name, "rb") as xlfile:
        byte_data = xlfile.read()

我在workbook.close()

之后添加了这些行

0 个答案:

没有答案