使用Python编写一个Excel文件,并从另一个Excel文件复制列 [英] Using Python, write an Excel file with columns copied from another Excel file
问题描述
有什么可以这样做的例子?
一些选项可供选择:
- xlwt (编写xls文件)
- xlrd (阅读xls / xlsx文件)
- openpyxl (阅读/写入xlsx文件)
- xlsxwriter (编写xlsx文件)
如果您只需复制数据(无格式化信息),则只需使用这些工具的任意组合进行阅读/写入即可。如果你有一个 xls
文件,你应该使用xlrd + xlwt选项。
以下是将现有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')
为索引,枚举值(数据):
sheet.write(0,索引,值)
workbook.save 'output.xls')
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.
Any examples on how I can do this please?
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)
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 xls
file, you should go with xlrd+xlwt option.
Here's a simple example of copying the first row from the existing excel file to the new one:
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')
这篇关于使用Python编写一个Excel文件,并从另一个Excel文件复制列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!