将 Pandas DataFrame 转换为 Excel

通过 json 数据将 Pandas DataFrame 转换为 Excel

以下是一个示例代码片段,演示如何使用 Aspose.Cells for Python via .NET 从 pandas DataFrame 导入数据到 Excel 文件:

  1. 创建示例的 pandas DataFrame 数据。
  2. 使用 pandas 库将 DataFrame 数据转换为 JSON 数据。
  3. 使用 Aspose.Cells for Python via .NET 导入 JSON 数据。
import pandas as pd
from aspose.cells.utility import JsonUtility, JsonLayoutOptions
from aspose.cells import Workbook, Worksheet, Cells
# Create a sample pandas DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'San Francisco', 'Los Angeles']}
df = pd.DataFrame(data)
# Convert pandas DataFrame to JSON
json_string = df.to_json(orient='records')
workbook = Workbook()
# Get the first worksheet
worksheet = workbook.worksheets[0]
# Get the cells
cells = worksheet.cells
options = JsonLayoutOptions()
unit = JsonUtility()
# Processes as table.
options.array_as_table = True
unit.import_data(json_string, cells, 0, 0, options)
workbook.save("out.xlsx")

直接将 Pandas DataFrame 转换为 Excel

以下是一个示例代码片段,演示如何使用 Aspose.Cells for Python via .NET 从 pandas DataFrame 导入数据到 Excel 文件:

  1. 创建示例的 pandas DataFrame 数据。
  2. 遍历 DataFrame 并使用 Aspose.Cells for Python via .NET 导入数据。
import pandas as pd
import aspose.cells
from aspose.cells import Workbook, CellsHelper, License
workbook = Workbook()
# Get the first worksheet
worksheet = workbook.worksheets[0]
# Get the cells
cells = worksheet.cells
# create a sample DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie', 'David'],
'age': [25, 32, 18, 47],
'city': ['New York', 'Paris', 'London', 'Berlin']}
df = pd.DataFrame(data)
rowindex = 0
colindex = 0
for column in df:
cell = cells.get(rowindex, colindex)
cell.put_value(df[column].name)
colindex += 1
for index, row in df.iterrows():
rowindex += 1
colindex = 0
cell = cells.get(rowindex, colindex)
cell.put_value(row["name"])
colindex += 1
cell = cells.get(rowindex, colindex)
cell.put_value(row["age"])
colindex += 1
cell = cells.get(rowindex, colindex)
cell.put_value(row["city"])
colindex += 1
workbook.save("out.xlsx")