简体   繁体   中英

Python append excel sheet from another workbook xlwt

I have read almost all the questions posted but still can't find any solution for it.

I have wb1.xls and wb2.xls.

All I want is to create wb3 with wb1.xls in sheet 1 and wb2 in sheet 2 but I can't seem to figure out .. Any help ?

import xlwt
import xlrd
import glob, os
import numpy as np
from xlutils.copy import copy

os.chdir("E:/docs/")

wb1=[file for file in glob.glob("wb1*")]
wb2=[file for file in glob.glob("wb2*")]

s1 = xlrd.open_workbook(filename = wb1[0])
s2 = xlrd.open_workbook(filename = wb2[0])

...

And I'm stuck here.... Any idea ? Note I'm working with xls not xlsx.

It would depend on the original workbooks. Are there any formulae that need to be transferred? Per cell formatting, fonts, styles, highlights, etc? If it is just raw data it is simple enough.

import xlrd
import xlwt

# open first excel file, store number of rows,cols and sheet name
wb_1 = open_workbook("file1.xls")
sheet_1 = wb.sheet_by_index(0)
maxRows_1 = sheet_1.nrows
maxCols_1 = sheet_1.ncols
sName_1 = sheet_1.name

i = 0
j = 0

# create output excel file
wb_out = xlwt.Workbook()
sheet_out_1 = wb_out.add_sheet(sName_1)

# Loop through writing each cell value
while i<maxRows_1:
    while j<maxCols_1:
        sheet_out_1.write(i,j, sheet_1.cell(i,j).value)
        j += 1
    j = 0
    i += 1

# repeat for second excel file
# then save your new excel 

wb_out.save("newFile.xls")

This will work as long as you are not concerned with styles and highlights ect.

This does not handle dates as excel stores them as floats. If you need to handle dates you will need to parse them. Consider this to help with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM