Как изменить формат столбца в Excel с python - PullRequest
1 голос
/ 30 марта 2020

Я хочу скопировать указанные c строки и столбцы с одного листа на другой методом "openpyxl". Но мой основной файл Excel - это файл .xlsb, а «openpyxl» не поддерживает файл .xlsb. Так что я строю этот сложный путь. (* Я не могу изменить .xlsb из Microsoft Excel в соответствии с правилами компании).

основной файл document.xlsb-> временный document.xlsx-> мой анализ document.xlsx

- Во-первых, я меняю формат данных .xlsb на .xlsx с помощью pandas.

-После этого из временного document.xlsx я беру определенные столбцы c и строки с методом openpyxl и вставьте в мой анализ document.xlsx

-Мой вопрос: я хочу изменить формат столбца D с "общего" на "короткую дату", и я новичок в Python. Не могли бы вы помочь мне с кодами? Кроме того, если я могу изменить ячейку формата в «.xlsb на .xlsx период преобразования», возможно, я смогу принять ввод от пользователя: «к какой дате вы хотите добавить« мой анализ документа.xlsx? »»

'основной документ.xlsx'

'временный документ.xlsx'

'my analysis 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()

Ответы [ 3 ]

3 голосов
/ 30 марта 2020

Да, посмотрите здесь в документах :

import xlsxwriter

workbook = xlsxwriter.Workbook('your_file.xlsx')
worksheet = workbook.add_worksheet()

cell_format05 = workbook.add_format()
cell_format05.set_num_format('mm/dd/yy')
worksheet.write(5, 0, 36892.521, cell_format05)  # output -> 01/01/01

# untested code for you, get your cells into column_D8_downwards array
# this is rather a structural code, not functional!
row = 0
for cell in column_D8_downwards:
    worksheet.write(row, 'D8', cell, cell_format_05)
    row=+1

workbook.close()

Так что итерируйте по всем ячейкам в вашем столбце (D8 вниз) и запишите старое значение в ячейку с новым формат.

Вот хороший пример.

0 голосов
/ 31 марта 2020

Проблема решена очень простым способом, я в шоке, когда решил ее.

1-Откройте "мой анализ документа.xlsx"

2-Выберите весь столбец "D"

Кнопка 3-Click home

Ячейка 4-формата-> Краткая дата

Даже если я обновляю данные Excel с помощью python, тип формата столбца не меняется.

Спасибо за поддержку.

0 голосов
/ 30 марта 2020

Вы также можете сделать то же самое после чтения данных с помощью pandas.DataFrame с помощью xlrd:

import xlrd
import pandas as pd

df = pd.read_csv('Your_File.csv')
df = df[6:].reset_index()
df.columns = df.iloc[0]

df['Date'] = df['Date_Int'].apply(lambda x: xlrd.xldate.xldate_as_datetime(x, 0))

print(df)

   TARİH       Date
0     43891 2020-03-01
1     43892 2020-03-02
2     43893 2020-03-03
3     43894 2020-03-04
4     43895 2020-03-05

Кроме того, вы можете изменить формат даты согласно вашему требованию .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...