在 excel 中创建 table - Python openpyxl
Create table in excel - Python openpyxl
有没有办法根据包含数据的所有行和列创建 table?通常 table 是通过放入固定引用创建的(例如:ref="A1:E5"))我需要的是找到最后一行的脚本sheet 并以此为参考。这是因为我需要编辑的 sheet 每次都包含不同数量的行,如果我设置固定引用,它将在 table.
中包含空行
如果在 excel 中将其作为宏,但想使用 openpyxl
将其转换为 python
Excel宏
Sub A2_SelectAllMakeTable()
lrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
lCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
ActiveSheet.ListObjects.Add(xlSrcRange, Range(Cells(1, 1), Cells(lrow, lCol)), , xlYes).Name = "Masterdata"
End Sub
python代码开始:
from openpyxl import load_workbook
wb = load_workbook('export1.XLSX')
ws1 = wb["Sheet1"]
ws1.title = "Masterdata"
您可以像这样创建 table -
tab = Table(displayName="Table1", ref="A1:E5")
# Add a default style with striped rows and banded columns
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
ws1.add_table(tab)
来自官方文档的示例 - https://openpyxl.readthedocs.io/en/stable/worksheet_tables.html
您可以在工作表 sheet
上使用 get_column_letter
、max_column
和 max_row
,如下所示:
from openpyxl.worksheet.table import Table
from openpyxl.utils import get_column_letter
table = Table(displayName="Table1", ref="A1:" + get_column_letter(sheet.max_column) + str(sheet.max_row))
sheet.add_table(table)
有没有办法根据包含数据的所有行和列创建 table?通常 table 是通过放入固定引用创建的(例如:ref="A1:E5"))我需要的是找到最后一行的脚本sheet 并以此为参考。这是因为我需要编辑的 sheet 每次都包含不同数量的行,如果我设置固定引用,它将在 table.
中包含空行如果在 excel 中将其作为宏,但想使用 openpyxl
将其转换为 pythonExcel宏
Sub A2_SelectAllMakeTable()
lrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
lCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
ActiveSheet.ListObjects.Add(xlSrcRange, Range(Cells(1, 1), Cells(lrow, lCol)), , xlYes).Name = "Masterdata"
End Sub
python代码开始:
from openpyxl import load_workbook
wb = load_workbook('export1.XLSX')
ws1 = wb["Sheet1"]
ws1.title = "Masterdata"
您可以像这样创建 table -
tab = Table(displayName="Table1", ref="A1:E5")
# Add a default style with striped rows and banded columns
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
ws1.add_table(tab)
来自官方文档的示例 - https://openpyxl.readthedocs.io/en/stable/worksheet_tables.html
您可以在工作表 sheet
上使用 get_column_letter
、max_column
和 max_row
,如下所示:
from openpyxl.worksheet.table import Table
from openpyxl.utils import get_column_letter
table = Table(displayName="Table1", ref="A1:" + get_column_letter(sheet.max_column) + str(sheet.max_row))
sheet.add_table(table)