按照本文使用 Python 创建 Excel 表。它包含设置 IDE 的详细信息、描述程序逻辑的步骤列表以及演示如何使用 Python 在 Excel 中制作表格的可运行示例代码。您将学习自定义表格并显示各种附加信息以丰富表格,例如自动显示值的总计。
使用 Python 将表添加到 Excel 的步骤
- 将IDE设置为Aspose.Cells for Python via Java以创建表
- 创建一个新的或加载具有表源数据的现有 Excel 文件
- 使用新 Excel 文件的示例数据填充 sheet
- 访问目标工作表并为数据范围添加 list object
- 使用 TableStyleType 枚举器设置表格样式
- 设置显示总标志和特定列中的值计数
- 使用格式化表格保存输出 Excel 文件
这些步骤描述如何使用 Python 在 Excel 中创建表格。通过访问包含数据的目标工作表并通过提供数据所在的单元格范围将列表对象添加为表格来开始该过程。创建表格后,根据要求设置表格样式和标志以显示总计和具体总计计算。
使用 Python 添加 Excel 表的代码
import jpype | |
import asposecells as cells | |
import random | |
jpype.startJVM() | |
from asposecells.api import License, Workbook, TableStyleType, TotalsCalculation | |
def create_sample_data(sheet): | |
# Fill workbook with some dummy data | |
titles = ["Employee", "Quarter", "Product", "Country", "Sale"] | |
employees = ["David", "James", "Miya"] | |
products = ["Chai", "Chang", "Geitost", "Maxilaku"] | |
countries = ["USA", "China", "Turkiye", "Germany", "India", "Italy"] | |
for idx, title in enumerate(titles): | |
sheet.getCells().get(0, idx).setValue(title) | |
for i in range(1, 20): | |
sheet.getCells().get(i, 0).setValue(random.choice(employees)) | |
sheet.getCells().get(i, 1).setValue(random.randint(1, 4)) | |
sheet.getCells().get(i, 2).setValue(random.choice(products)) | |
sheet.getCells().get(i, 3).setValue(random.choice(countries)) | |
sheet.getCells().get(i, 4).setValue(random.randint(0, 2000)) | |
# Instantiate a license | |
license = License() | |
license.setLicense("License.lic") | |
# Create a workbook. | |
wb = Workbook() | |
# Optionally call this function if workbook has no data | |
create_sample_data(wb.getWorksheets().get(0)) | |
# Obtain the first sheet | |
sheet = wb.getWorksheets().get(0) | |
# Add a new list object with 20 rows and 5 columns | |
listObject = sheet.getListObjects().get(sheet.getListObjects().add("A1", "E20", True)) | |
# Set table style | |
listObject.setTableStyleType(TableStyleType.TABLE_STYLE_MEDIUM_10) | |
# Show the flag to display the Total for all numbers | |
listObject.setShowTotals(True) | |
# Set the second column calculation type | |
listObject.getListColumns().get(1).setTotalsCalculation(TotalsCalculation.COUNT) | |
# Saving the Excel file | |
wb.save("output.xlsx") | |
print("Table created successfully!!!") |
此代码片段显示如何使用 Python 在 Excel 中创建数据表。 create_sample_data() 方法是可选的,如果 Excel 文件已有所需数据,则可以跳过该方法。利用 TableStyleType 枚举器建立表格样式,并选择 TotalsCalculation 选项之一,例如此代码片段中演示的 COUNT。您可以从上述枚举器提供的其他类型中进行选择。
本文教我们创建 Excel 表格并设置其格式。要创建数据透视表,请参阅有关 如何在Python中创建数据透视表 的文章。