【问题标题】:Is it possible to read data from an Excel sheet in Python using Xlsxwriter? If so how?是否可以使用 Xlsxwriter 从 Python 中的 Excel 工作表中读取数据?如果有怎么办?
【发布时间】:2013-12-27 17:32:40
【问题描述】:

我正在做以下计算。

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

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

【问题讨论】:

  • 我不认为你可以和作家一起阅读,你应该找一个reader...检查这个question
  • Scipy中有Excel阅读能力。

标签: python xlsxwriter


【解决方案1】:

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

有一些alternatives listed in the documentation

【讨论】:

  • 以上链接不再有效。我相信this 是新页面:
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    如果您想使用 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      相关资源
      最近更新 更多