I want to copy an specific rows and columns one sheet to another with "openpyxl" method. But my main excel file is .xlsb file and "openpyxl" is not supporting .xlsb file.So I build that complicated way. (* I can not change the .xlsb from Microsoft Excel according to company rules).
main document.xlsb file->temporary document.xlsx->my analyse document.xlsx
-Firstly, I' m changing the data format .xlsb to .xlsx with pandas.
-After that, from temporary document.xlsx, I' m taking specific columns and rows with openpyxl method and paste to my analyse document.xlsx
-My question is: I want to change D column format from "general" to "short date" and I am beginner at Python. Would you please help me about codes? Also if I can change the format cell in ".xlsb to .xlsx tranformation period" maybe I can take input from user: "which date do you want to append 'my analyse document.xlsx?'"
'main document.xlsx'
'temporary document.xlsx'
'my analyse document.xlsx'
import pandas as pd
import openpyxl
df = pd.read_excel("main document.xlsb",sheet_name="Data", engine="pyxlsb")
df.to_excel("temporary document.xlsx")
#! Python 3
# - Copy and Paste Ranges using OpenPyXl library
# Prepare the spreadsheets to copy from and paste too.
# File to be copied
wb = openpyxl.load_workbook("temporary document.xlsx") # Add file name
sheet = wb["Sheet1"] # Add Sheet name
# File to be pasted into
template = openpyxl.load_workbook("my analyse document.xlsx") # Add file name
temp_sheet = template["Sheet2"] # Add Sheet name
# Copy range of cells as a nested list
# Takes: start cell, end cell, and sheet you want to copy from.
def copyRange(startCol, startRow, endCol, endRow, sheet):
rangeSelected = []
# Loops through selected Rows
for i in range(startRow, endRow + 1, 1):
# Appends the row to a RowSelected list
rowSelected = []
for j in range(startCol, endCol + 1, 1):
rowSelected.append(sheet.cell(row=i, column=j).value)
# Adds the RowSelected List and nests inside the rangeSelected
rangeSelected.append(rowSelected)
return rangeSelected
# Paste range
# Paste data from copyRange into template sheet
def pasteRange(startCol, startRow, endCol, endRow, sheetReceiving, copiedData):
countRow = 0
for i in range(startRow, endRow + 1, 1):
countCol = 0
for j in range(startCol, endCol + 1, 1):
sheetReceiving.cell(row=i, column=j).value = copiedData[countRow][countCol]
countCol += 1
countRow += 1
def createData():
print("Processing...")
selectedRange = copyRange(2, 2011, 183, 2274, sheet) # Change the 4 number values (startCol, startRow, endCol, endRow, sheet)
pastingRange = pasteRange(2, 4573, 182, 4836, temp_sheet, selectedRange) # Change the 4 number values (startCol, startRow, endCol, endRow, sheet)
# You can save the template as another file to create a new file here too.s
template.save("my analyse document.xlsx")
print("Range copied and pasted!")
go= createData()