使用 Python 编写一个 Excel 文件,其中包含从另一个 Excel 文件复制的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16560289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Python, write an Excel file with columns copied from another Excel file
提问by salamey
I have an Excel file containing a varying number of columns, I would like to loop through certain columns (from their header row value) of that file using Python, then write (copy) those columns to another Excel file.
我有一个包含不同列数的 Excel 文件,我想使用 Python 遍历该文件的某些列(从它们的标题行值),然后将这些列写入(复制)到另一个 Excel 文件中。
Any examples on how I can do this please?
任何关于我如何做到这一点的例子?
采纳答案by alecxe
Here are some options to choose from:
以下是一些可供选择的选项:
- xlwt(writing xls files)
- xlrd(reading xls/xlsx files)
- openpyxl(reading/writing xlsx files)
- xlsxwriter(writing xlsx files)
- xlwt(写入 xls 文件)
- xlrd(读取 xls/xlsx 文件)
- openpyxl(读取/写入 xlsx 文件)
- xlsxwriter(写入 xlsx 文件)
If you need to copy only data (without formatting information), you can just use any combination of these tools for reading/writing. If you have an xlsfile, you should go with xlrd+xlwt option.
如果您只需要复制数据(没有格式信息),您可以使用这些工具的任意组合进行读/写。如果你有一个xls文件,你应该使用 xlrd+xlwt 选项。
Here's a simple example of copying the first row from the existing excel file to the new one:
这是将第一行从现有 excel 文件复制到新文件的简单示例:
import xlwt
import xlrd
workbook = xlrd.open_workbook('input.xls')
sheet = workbook.sheet_by_index(0)
data = [sheet.cell_value(0, col) for col in range(sheet.ncols)]
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('test')
for index, value in enumerate(data):
sheet.write(0, index, value)
workbook.save('output.xls')

