使用Python编写一个Excel文件,并从另一个Excel文件复制列 [英] Using Python, write an Excel file with columns copied from another Excel file

查看:308
本文介绍了使用Python编写一个Excel文件,并从另一个Excel文件复制列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含不同数量列的Excel文件,我想使用Python循环访问该文件的某些列(从它们的标题行值),然后将这些列写入(复制)到另一个Excel文件。 p>

有什么可以这样做的例子?

解决方案

一些选项可供选择:





如果您只需复制数据(无格式化信息),则只需使用这些工具的任意组合进行阅读/写入即可。如果你有一个 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:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆