是否可以使用Xlsxwriter从Python中读取Excel工作表中的数据?如果是这样的话?

问题描述 投票:9回答:3

我正在做以下计算。

worksheet.write_formula('E5', '=({} - A2)'.format(number))

我想在控制台上打印E5中的值。你能帮帮我吗?是否可以使用Xlsxwriter或者我应该使用不同的库?

python xlsxwriter
3个回答
12
投票

使用XlsxWriter无法从Excel文件中读取数据。

有一些alternatives listed in the documentation


0
投票

没有回答这个具体问题,只是一个建议 - 只需尝试pandas并从excel中读取数据。此后,您可以使用pandas DataFrame内置方法简单地操作数据:

df = pd.read_excel(file_,index_col=None, header=0)

df是pandas.DataFrame,只需通过它的cookbook site进行DataFrame。如果你不知道这个包,你可能会对这个令人敬畏的python模块感到惊讶。


0
投票

如果你想使用xlsxwriter来操作你不能用pandas做的格式和公式,你至少可以使用pandas将excel文件导入到xlsxwriter对象中。这是如何做。

import pandas as pd
import xlsxwriter   

def xlsx_to_workbook(xlsx_in_file_url, xlsx_out_file_url, sheetname):
    """
    Read EXCEL file into xlsxwriter workbook worksheet
    """
    workbook = xlsxwriter.Workbook(xlsx_out_file_url)
    worksheet = workbook.add_worksheet(sheetname)
    #read my_excel into a pandas DataFrame
    df = pd.read_excel(xlsx_in_file_url)
    # A list of column headers
    list_of_columns = df.columns.values

    for col in range(len(list_of_columns)):
        #write column headers.
        #if you don't have column headers remove the folling line and use "row" rather than "row+1" in the if/else statments below
        worksheet.write(0, col, list_of_columns[col] )
        for row in range (len(df)):
            #Test for Nan, otherwise worksheet.write throws it.
            if df[list_of_columns[col]][row] != df[list_of_columns[col]][row]:
                worksheet.write(row+1, col, "")
            else:
                worksheet.write(row+1, col, df[list_of_columns[col]][row])
    return workbook, worksheet

# Create a workbook
#read you Excel file into a workbook/worksheet object to be manipulated with xlsxwriter
#this assumes that the EXCEL file has column headers
workbook, worksheet = xlsx_to_workbook("my_excel.xlsx", "my_future_excel.xlsx", "My Sheet Name")

###########################################################
#Do all your fancy formatting and formula manipulation here
###########################################################

#write/close the file my_new_excel.xlsx
workbook.close()
© www.soinside.com 2019 - 2024. All rights reserved.