ReportLab 表格在一页内显示:调整尺寸和分割表格
要让 reportlab 的表格显示在一页上,您可以使用以下方法之一:\n\n1. 调整表格的宽度和高度:通过设置表格的 width 和 height 属性,可以调整表格的大小,使其适应页面。确保表格的总宽度不超过页面宽度,并使表格的高度不超过页面高度。\n\npython\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.lib import colors\nfrom reportlab.platypus import SimpleDocTemplate, Table\n\ndata = [['Cell 1', 'Cell 2', 'Cell 3'],\n ['Cell 4', 'Cell 5', 'Cell 6'],\n ['Cell 7', 'Cell 8', 'Cell 9']]\n\ntable = Table(data, colWidths=100, rowHeights=30)\ntable.setStyle([('BACKGROUND', (0, 0), (-1, -1), colors.grey)])\n\ndoc = SimpleDocTemplate("table.pdf", pagesize=letter)\ndoc.build([table])\n\n\n2. 分割表格为多个子表格:如果表格的列数较多,可以将表格分割成多个子表格,并在页面上逐个显示。这样可以确保每个子表格都适应页面。\n\npython\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.lib import colors\nfrom reportlab.platypus import SimpleDocTemplate, Table, TableStyle\n\ndata = [['Cell 1', 'Cell 2', 'Cell 3'],\n ['Cell 4', 'Cell 5', 'Cell 6'],\n ['Cell 7', 'Cell 8', 'Cell 9'],\n ['Cell 10', 'Cell 11', 'Cell 12'],\n ['Cell 13', 'Cell 14', 'Cell 15']]\n\ntable = Table(data, colWidths=100, rowHeights=30)\ntable.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.grey)]))\n\ndoc = SimpleDocTemplate("table.pdf", pagesize=letter)\n\n# Split table into smaller sub-tables\nsplit_table = table.split(doc.width, doc.height)\n\n# Build each sub-table on a separate page\nfor sub_table in split_table:\n doc.build([sub_table])\n\n\n这两种方法都可以使表格显示在一页上,选择适合您需求的方法即可。
原文地址: https://www.cveoy.top/t/topic/pW2y 著作权归作者所有。请勿转载和采集!