如何在Excel中更改列格式

问题描述 投票:0回答:2

我想使用“ openpyxl”方法将特定的行和列从一张纸复制到另一张纸。但是我的主要excel文件是.xlsb文件,“ openpyxl”不支持.xlsb文件。因此,我构建了这种复杂的方法。 (*我不能根据公司规则从Microsoft Excel更改.xlsb。)>

主document.xlsb文件->临时document.xlsx->我的分析document.xlsx

-首先,我使用熊猫将数据格式.xlsb更改为.xlsx。

-之后,从临时document.xlsx,我使用openpyxl方法获取特定的列和行,并粘贴到我的分析document.xlsx中

--我的问题是:我想将D列格式从“常规”更改为“短日期”,我是Python的初学者。您能帮我找些代码吗?另外,如果我可以将“ .xlsb转换为.xlsx转换期”中的格式单元格,也许我可以从用户那里获取输入:“您要在哪个日期附加'我的分析document.xlsx?']

'main document.xlsx'

'temporary document.xlsx'

'我的分析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()

我想使用“ openpyxl”方法将特定的行和列从一张纸复制到另一张纸。但是我的主要excel文件是.xlsb文件,“ openpyxl”不支持.xlsb文件。因此,我构建了一个复杂的...

python excel pandas openpyxl xlsxwriter
2个回答
3
投票

是的,在docs中查看:


0
投票

您也可以在pandas.DataFrame的帮助下使用xlrd读取数据后执行相同的操作:

© www.soinside.com 2019 - 2024. All rights reserved.