Konvertera NumPy till Excel
Contents
[
Hide
]
Med hjälp av Aspose.Cells for Python via .NET API kan du konvertera NumPy-array till Excel, OpenOffice, Pdf, Json och många olika format.
Konvertera NumPy-array till Excel
Här är ett exempel på ett kodavsnitt för att demonstrera hur man importerar data från en NumPy-array till en Excel-fil med Aspose.Cells for Python via .NET:
- Skapa ett exempel på NumPy-matrisdata.
- Gå igenom NumPy-matrisen och importera data med Aspose.Cells for Python via .NET.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from aspose.cells import Workbook, Worksheet | |
def put_value(cells, raw_value, row , column): | |
cell = cells.get(row , column) | |
dtype = type(raw_value) | |
match dtype: | |
case np.bool_ : | |
value = bool(raw_value) | |
case np.int_ : | |
value = int(raw_value) | |
case np.intc : | |
value = int(raw_value) | |
case np.intp : | |
value = int(raw_value) | |
case np.int8 : | |
value = int(raw_value) | |
case np.int16 : | |
value = int(raw_value) | |
case np.int32 : | |
value = int(raw_value) | |
case np.int64 : | |
value = int(raw_value) | |
case np.uint8 : | |
value = int(raw_value) | |
case np.uint16 : | |
value = int(raw_value) | |
case np.uint32 : | |
value = int(raw_value) | |
case np.uint64 : | |
value = int(raw_value) | |
case np.float_: | |
value = int(raw_value) | |
case np.float16: | |
value = float(raw_value) | |
case np.float32: | |
value = float(raw_value) | |
case np.float64: | |
value = float(raw_value) | |
case np.single: | |
value = float(raw_value) | |
case np.double: | |
value = float(raw_value) | |
case np.datetime64 : | |
ts = pd.to_datetime(str(raw_value)) | |
value = ts.strftime('%Y.%m.%d') | |
case _: | |
value = raw_value | |
cell.put_value(value) | |
pass | |
# Create a sample NumPy array | |
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) | |
# Create a new Aspose.Cells Workbook | |
workbook = Workbook() | |
# Access the first (default) worksheet | |
worksheet = workbook.worksheets[0] | |
# Get the cells | |
cells = worksheet.cells | |
# Import data from NumPy array to the worksheet | |
rowindex = -1 | |
colindex = 0 | |
for row in data: | |
rowindex += 1 | |
colindex = 0 | |
for item in row: | |
put_value(cells, item, rowindex, colindex) | |
print(item) | |
colindex += 1 | |
# Save the Excel file | |
workbook.save("out.xlsx") |