【问题标题】:how to extract data from one excel workbook and output to another using python xlrd/xlwt?如何使用 python xlrd/xlwt 从一个 Excel 工作簿中提取数据并输出到另一个工作簿?
【发布时间】:2016-07-01 01:06:25
【问题描述】:

我正在尝试编写一个脚本来自动复制/粘贴员工时间表 从几个文件到一个编译文件。由于它们是带有项目代码的时间表,因此某些单元格留空,其中员工当天从事不同的项目。此外,文件已从 xlsx(2007) 转换为 .csv.xls,xlrd 似乎可以正常打开。

我确实知道如何打开和创建书籍对象,但我对这个模块的了解非常有限,所以我认为一般算法可能会有所帮助:

import xlrd, xlwt

put all following in for or while loop to iterate through files:
book = xlrd.open_workbook('mybook.csv.xls')
extract data; store data for ouput
use for loop to iterate over data, output to final sheet
open next file, repeat process storing each output below the previous

我正在寻找可以帮助我找到答案的任何东西,而不仅仅是代码。 任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 另外我正在尝试读取包含 str 和 float dtypes 的列 {A:T} 和行 {3:27}。我很确定现有值和 nan 或 null 任何空白空间的类型为 string 的列表很容易使用。
  • 要在 python 中读取/写入 xlsx 文件,请使用 openpyxl (bitbucket.org/ericgazoni/openpyxl/downloads)。然而,真正的解决方案是停止让员工将他们的时间表存储在 Excel 文件中!
  • 确实如此。谢谢,我会检查 openpyxl。我也已经解决了这个问题的大部分,所以除非你真的想这样做;不需要更多信息,但谢谢!

标签: python excel xlrd xlwt


【解决方案1】:

这可能会有所帮助...它尽可能地重现您的数据(日期保留为日期,空单元格不会变成内容长度为 0 的文本单元格,布尔值和错误单元格不会变成数字单元格)。

from xlrd import XL_CELL_EMPTY, XL_CELL_TEXT, XL_CELL_NUMBER,
    XL_CELL_DATE, XL_CELL_BOOLEAN, XL_CELL_ERROR, open_workbook
from xlwt import Row, easyxf, Workbook

method_for_type = {
    XL_CELL_TEXT:    Row.set_cell_text,
    XL_CELL_NUMBER:  Row.set_cell_number,
    XL_CELL_DATE:    Row.set_cell_number,
    XL_CELL_ERROR:   Row.set_cell_error,
    XL_CELL_BOOLEAN: Row.set_cell_boolean,
    }

date_style = easyxf(num_format_str='yyyy-mm-dd')
other_style = easyxf(num_format_str='General')

def append_sheet(rsheet, wsheet, wrowx=0):
    for rrowx in xrange(rsheet.nrows):
        rrowvalues = rsheet.row_values(rrowx)
        wrow = wsheet.row(wrowx)
        for rcolx, rtype in enumerate(rsheet.row_types(rrowx)):
            if rtype == XL_CELL_EMPTY: continue
            wcolx = rcolx
            wmethod = method_for_type[rtype]
            wstyle = date_style if rtype == XL_CELL_DATE else other_style
            wmethod(wrow, wcolx, rrowvalues[rcolx], wstyle) 
        wrowx += 1
    return wrowx

if __name__ == '__main__':
    import sys, xlrd, xlwt, glob
    rdpattern, wtfname = sys.argv[1:3]
    wtbook = Workbook()
    wtsheet = wtbook.add_sheet('guff')
    outrowx = 0
    for rdfname in glob.glob(rdpattern):
        rdbook = open_workbook(rdfname)
        rdsheet = rdbook.sheet_by_index(0)
        outrowx = append_sheet(rdsheet, wtsheet, outrowx)
        print outrowx
    wtbook.save(wtfname)

【讨论】:

  • 其实我是要给你发邮件的! .csv.xls 是通过使用扩展名 .csv “另存为”从 xl2007 转换为 csv 的文件的扩展名,我希望与您联系是试用 2007 年的测试版 xlsxrd,因为所有文件我正在处理的是 2007 年。这对整个部门来说都很棒,因为我们几乎都是 python 用户!我也一直在尝试 openpyxl,但 xlrd 对我(初学者)来说更容易理解并开始使用更全面的文档,如果可能的话,它会非常受欢迎。
  • @Corey:我会在知道您的电子邮件地址后立即将 xlsxrd 测试版发送给您。
  • wcpapine | mtu.edu,非常感谢!我们会好好利用它。
【解决方案2】:

我正在为 xlutils、xlrd 和 xlwt 创建一个名为 excel 函数的类,我最终可能会创建一个库。如果您有兴趣帮助我尝试制作删除工作表功能。

您可能希望转向 openpyxl 和/或 pyexcel,因为它们更容易并且具有此功能。

这里是如何使用 open pyxl 进行复制:Copy whole worksheet with openpyxl

这里是 pyexcel 的文档,它是 xlwt、xlrd 和 xlutils 的包装器:https://pyexcel.readthedocs.io/en/latest/

如果您想从一个 Excel 工作簿中提取数据并输出到另一个工作簿,您需要使用 createCopy(original workbook, other workbook, original filename, new filename)

import xlwt
import xlrd
import xlutils.copy
import xlutils class excelFunctions():

def getSheetNumber(self, fileName, sheetName):

    # opens existing workbook
    workbook = xlrd.open_workbook(fileName, on_demand=True)

    #turns sheet name into sheet number       
    for index, sheet in enumerate(workbook.sheet_names()):
        if sheet == sheetName:
            return index


def createSheet(self, fileName, sheetName):

    # open existing workbook
    rb = xlrd.open_workbook(fileName, formatting_info=True, on_demand=True)

    # make a copy of it
    wb = xl_copy(rb)

    # creates a variable called sheets which stores all the sheet names
    sheets = rb.sheet_names()

    # creates a string which is equal to the sheetName user input
    str1 = sheetName

    # checks to see if the given sheetName is a current sheet
    if (str1 not in sheets):

        # add sheet to workbook with existing sheets
        Sheet = wb.add_sheet(sheetName)

        # save the sheet with the same file name as before
        wb.save(fileName)

    else:
        # this declares the sheet variable to be equal to the sheet name the user gives
        sheet = wb.get_sheet(self.getSheetNumber(fileName, sheetName))

        # save the sheet with the same file name as before
        wb.save(fileName)



def createCopy(self, fileName, fileName2, sheetName, sheetName2):


    # open existing workbook
    rb = xlrd.open_workbook(fileName, formatting_info=True)

    # defines sheet as the name of the sheet given
    sheet = rb.sheet_by_name(sheetName)

    # makes a copy of the original sheet
    wb = xl_copy(rb)

    # creates an int called column_count which is equal to the sheets maximum columns 
    column_count = sheet.ncols - 1

    # creates a blank array called stuff
    Stuff = []

    # this loops through adding columns from the given sheet name
    for i in range (0, column_count):
        Stuff.append([sheet.cell_value(row, i) for row in range(sheet.nrows)])

    # create a sheet if there is not already a sheet    
    self.createSheet(fileName, sheetName2)

    # defines sheet as the new sheet
    sheet = wb.get_sheet(self.getSheetNumber(fileName, sheetName2))

    # this writes to the sheet
    for colidx, col in enumerate(Stuff):
        for rowidx, row in enumerate(col):
            sheet.write(rowidx, colidx, row)

    # this saves the file
    wb.save(fileName2)

【讨论】:

  • 你好尼克,很抱歉回复晚了......我今天刚在这里登记,显然已经有一段时间了,非常长的一段时间。你怎么过来的?你继续努力了吗?我现在正在清理 python,很想听听你的消息……我的电子邮件仍然是一样的,位于上面的 cmets 中……(撤消那一点天才有点太晚了)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多