91 lines
2.9 KiB
Python
91 lines
2.9 KiB
Python
from openpyxl.styles import Alignment
|
|
|
|
def center_columns(worksheet, columns):
|
|
"""
|
|
Center the content of specified columns in a worksheet.
|
|
|
|
Parameters:
|
|
worksheet: The worksheet object from openpyxl.
|
|
columns (list of str): List of column letters to be centered, e.g., ['B', 'D', 'E'].
|
|
"""
|
|
for col_letter in columns:
|
|
for cell in worksheet[col_letter]:
|
|
cell.alignment = Alignment(horizontal='center')
|
|
|
|
|
|
from openpyxl import Workbook
|
|
from openpyxl.utils import get_column_letter
|
|
|
|
def autosize_columns(worksheet, columns):
|
|
"""
|
|
Adjust the column width to the maximum content size of specified columns in a worksheet.
|
|
|
|
Parameters:
|
|
worksheet: The worksheet object from openpyxl.
|
|
columns (list of str): List of column letters to be resized, e.g., ['A', 'C', 'F'].
|
|
"""
|
|
for col_letter in columns:
|
|
max_length = 0
|
|
col = worksheet[col_letter]
|
|
for cell in col:
|
|
try:
|
|
if len(str(cell.value)) > max_length:
|
|
max_length = len(str(cell.value))
|
|
except:
|
|
pass
|
|
adjusted_width = (max_length + 2) * 1.2 # Adding a little extra width
|
|
worksheet.column_dimensions[col_letter].width = adjusted_width
|
|
|
|
|
|
from openpyxl import load_workbook
|
|
|
|
def open_worksheet(file_path, sheet_name):
|
|
"""
|
|
Opens an Excel file and returns a specific worksheet by name.
|
|
|
|
Parameters:
|
|
file_path (str): The path to the Excel file.
|
|
sheet_name (str): The name of the worksheet to load.
|
|
|
|
Returns:
|
|
worksheet: The loaded worksheet object, or None if the sheet does not exist.
|
|
"""
|
|
try:
|
|
# Cargar el libro de trabajo desde el archivo especificado
|
|
workbook = load_workbook(filename=file_path)
|
|
|
|
# Intentar obtener la hoja de trabajo por nombre
|
|
if sheet_name in workbook.sheetnames:
|
|
worksheet = workbook[sheet_name]
|
|
return workbook, worksheet
|
|
else:
|
|
print(f"Sheet named '{sheet_name}' does not exist in the workbook.")
|
|
return None, None
|
|
except FileNotFoundError:
|
|
print(f"No such file: '{file_path}'")
|
|
return None, None
|
|
except Exception as e:
|
|
print(f"An error occurred: {e}")
|
|
return None, None
|
|
|
|
|
|
def save_workbook(workbook, file_path):
|
|
"""
|
|
Saves the modified workbook to a specified file path.
|
|
|
|
Parameters:
|
|
workbook: The openpyxl workbook object that has been modified.
|
|
file_path (str): The file path where the workbook should be saved.
|
|
|
|
Returns:
|
|
bool: True if the workbook was saved successfully, False otherwise.
|
|
"""
|
|
try:
|
|
workbook.save(file_path)
|
|
print(f"Workbook saved successfully to '{file_path}'.")
|
|
return True
|
|
except Exception as e:
|
|
print(f"Failed to save the workbook. Error: {e}")
|
|
return False
|
|
|