import openpyxl
def array_to_excel(array, filename='output.xlsx', sheet_name='Sheet1'):
# Create a workbook and select the active worksheet
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = sheet_name
# Iterate through the array and write each value to the Excel sheet
for row_index, row in enumerate(array, start=1):
for column_index, value in enumerate(row, start=1):
sheet.cell(row=row_index, column=column_index, value=value)
# Save the workbook to a file
workbook.save(filename)
# Example usage
array = [
['Header1', 'Header2', 'Header3'],
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
array_to_excel(array, 'example.xlsx')
import openpyxl
def array_to_excel(array, filename='output.xlsx', sheet_name='Sheet1', column_widths=None, row_heights=None):
# Create a workbook and select the active worksheet
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = sheet_name
# Set column widths if specified
if column_widths:
for i, width in enumerate(column_widths, start=1):
column_letter = openpyxl.utils.get_column_letter(i)
sheet.column_dimensions[column_letter].width = width
# Set row heights if specified
if row_heights:
for i, height in enumerate(row_heights, start=1):
sheet.row_dimensions[i].height = height
# Iterate through the array and write each value to the Excel sheet
for row_index, row in enumerate(array, start=1):
for column_index, value in enumerate(row, start=1):
sheet.cell(row=row_index, column=column_index, value=value)
# Save the workbook to a file
workbook.save(filename)
# Example usage
array = [
['Header1', 'Header2', 'Header3'],
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Set desired column widths and row heights
column_widths = [15, 20, 25] # Widths for columns A, B, C
row_heights = [20, 30, 40, 50] # Heights for rows 1, 2, 3, 4
array_to_excel(array, 'example.xlsx', column_widths=column_widths, row_heights=row_heights)
By running the updated script, you'll generate an Excel file where the column widths and row heights are adjusted according to the specified lists. Adjust column_widths and row_heights to fit your data's formatting needs.