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

时间:2013-12-10 09:20:59

标签: python xlsxwriter

我正在进行以下计算。

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

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

3 个答案:

答案 0 :(得分:12)

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

有一些alternatives listed in the documentation

答案 1 :(得分:0)

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

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

df是pandas.DataFrame,只需从cookbook site开始通过DataFrame。如果您不知道此软件包,则可能会对这个很棒的python模块感到惊讶。

答案 2 :(得分:0)

如果要使用xlsxwriter来处理熊猫无法使用的格式和公式,则至少可以使用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()