Pol*_*Geo 2 python excel xlrd xlwt xlutils
使用下面的 Python 测试代码,我尝试将 Excel ( *.xls) 文件中的唯一工作表复制到包含一个工作表的新 Excel 文件中。
输入电子表格如下所示:
from copy import deepcopy
from xlrd import open_workbook
from xlutils.copy import copy as copy
from xlwt import Workbook
rb = open_workbook(r"C:\Temp\test1.xls",formatting_info=True)
wb = copy(rb)
new_book = Workbook()
r_sheet = rb.sheet_by_index(0)
sheets = []
w_sheet = deepcopy(wb.get_sheet(0))
w_sheet.set_name("test1")
for row_index in range(0, r_sheet.nrows):
for col_index in range(0, r_sheet.ncols):
cell_value = r_sheet.cell(row_index, col_index).value
print cell_value
w_sheet.write(row_index, col_index, cell_value)
sheets.append(w_sheet)
new_book._Workbook__worksheets = sheets
new_book.save(r"C:\Temp\test2.xls")
Run Code Online (Sandbox Code Playgroud)
如果我运行代码,它会显示下面的输出,并使用名为 test1 的工作表创建新的 Excel 文件。
Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Col1
Col2
Col3
a
1.0
X
b
2.0
Y
c
3.0
Z
>>>
Run Code Online (Sandbox Code Playgroud)
不幸的是,输出似乎写入了正确数量的单元格,但所有非数字单元格值都写为#VALUE!.
使用 Python 2.7.10,是否有一种简单的方法可以从一个 XLS 读取工作表,然后将其作为工作表写入另一个 XLS 文件中?
我不想简单地复制电子表格,然后在新电子表格中重命名工作表,因为一旦我可以让它工作,我想复制十几个电子表格中的每个电子表格中的唯一工作表,以成为电子表格中同名的工作表有十几个工作表。
from xlrd import open_workbook
from xlutils.copy import copy
# Read the workbook
rb = open_workbook("input.xls", formatting_info=True)
# Copy into a new workbook
wb = copy(rb)
# Rename to 'test1' as the original post asked for
ws = wb.get_sheet(0)
ws.name = 'test1'
# Save the new workbook
wb.save("output.xls")
Run Code Online (Sandbox Code Playgroud)