ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – xlsxwriter:有没有办法在我的工作簿中打开现有的工作表?

2019-09-23 17:59:36  阅读:1128  来源: 互联网

标签:python xlsxwriter worksheet


我能够打开已有的工作簿,但是我没有看到任何方法在该工作簿中打开预先存在的工作表.有没有办法做到这一点?

解决方法:

您无法使用xlsxwriter附加到现有的xlsx文件.

有一个名为openpyxl的模块允许您读取和写入预先存在的excel文件,但我确信这样做的方法包括从excel文件中读取,以某种方式存储所有信息(数据库或数组),然后重写您调用workbook.close(),然后将所有信息写入xlsx文件.

同样,您可以使用自己的方法“附加”到xlsx文档.我最近不得不附加到xlsx文件,因为我有很多不同的测试,其中GPS数据进入主工作表,然后每次测试开始时我都必须添加一个新的工作表.我没有openpyxl可以解决这个问题的唯一方法是用xlrd读取excel文件,然后遍历行和列……

cells = []
for row in range(sheet.nrows):
    cells.append([])
    for col in range(sheet.ncols):
        cells[row].append(workbook.cell(row, col).value)

但是,您不需要数组.例如,这非常好用:

import xlrd
import xlsxwriter

from os.path import expanduser
home = expanduser("~")

# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
    for col in range(20):
        sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()

# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()

# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))

# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
    newSheet = wb.add_worksheet(sheet.name)
    for row in range(sheet.nrows):
        for col in range(sheet.ncols):
            newSheet.write(row, col, sheet.cell(row, col).value)

for row in range(10, 20): # write NEW data
    for col in range(20):
        newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes

但是,我发现读取数据并存储到二维数组更容易,因为我正在操作数据并一遍又一遍地接收输入,并且在测试结束之前不想写入excel文件(你可以轻松地使用xlsxwriter,因为这可能是他们在你调用.close()之前所做的事情.

标签:python,xlsxwriter,worksheet
来源: https://codeday.me/bug/20190923/1815334.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有