Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python, write an Excel file with columns copied from another Excel file [closed]

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?

like image 222
salamey Avatar asked May 15 '13 08:05

salamey


People also ask

Can you pull data from a closed Excel file?

Extracting data from a closed file in another workbook is a common request by most of the excel user. They would like to pull or consolidate data from closed files; however, this is not possible.

How do I copy a sheet from one Excel file to another in Python?

Python | How to copy data from one Excel sheet to another 1) Import openpyxl library as xl. 2) Open the source excel file using the path in which it is located. 3) Open the required worksheet to copy using the index of it.

How do you make Excel pull data from another workbook?

Type = (equal sign). Switch to the source workbook, and then click the worksheet that contains the cells that you want to link. Press F3, select the name that you want to link to and press Enter.


1 Answers

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') 
like image 51
alecxe Avatar answered Sep 16 '22 14:09

alecxe