使用python调整列宽度的逻辑需要自己写,这里是参考参考文章
中的内容,使用openpyxl
打开文件后,将列宽度根据列的内容进行指定,使用max(列的内容宽度 + 2) * 1.2
来指定列宽
示例程序
假设有一个测试.xlsx
的文件,使用如下程序自适应的调整列宽度
import openpyxldef auto_resize_column(excel_path):"""自适应列宽度"""wb = openpyxl.load_workbook(excel_path)worksheet = wb.activefor col in worksheet.columns:max_length = 0column = col[0].column_letter # Get the column namefor cell in col:try: # Necessary to avoid error on empty cellsif len(str(cell.value)) > max_length:max_length = len(str(cell.value))except:passadjusted_width = (max_length + 2) * 1.2worksheet.column_dimensions[column].width = adjusted_widthwb.save(excel_path)def main():excel = auto_resize_column("测试.xlsx")if __name__ == '__main__':main()
参考文章
- https://stackoverflow.com/questions/39529662/python-automatically-adjust-width-of-an-excel-files-columns