杰瑞科技汇

Python如何处理Excel中的数字?

Of course! It seems you're asking about working with numbers in Excel using Python. This is a very common task, and the most popular library for this is openpyxl.

Python如何处理Excel中的数字?-图1
(图片来源网络,侵删)

I'll guide you through the most common operations: reading numbers from an Excel file, writing numbers to an Excel file, and handling common issues like number formatting.

Installing the Library

First, you need to install openpyxl. Open your terminal or command prompt and run:

pip install openpyxl

Reading Numbers from an Excel File

Let's say you have an Excel file named sales_data.xlsx with the following data:

Product Sales Date
Apples 75 2025-10-25
Oranges 50 2025-10-26
Bananas 25 2025-10-27

Here is the Python code to read these numbers:

Python如何处理Excel中的数字?-图2
(图片来源网络,侵删)
from openpyxl import load_workbook
# Load the existing workbook
workbook = load_workbook('sales_data.xlsx')
# Select the active sheet (or you can use sheet name)
sheet = workbook.active
# --- Reading numbers ---
# Get the value from a specific cell, e.g., B2 (Sales for Apples)
sales_value = sheet['B2'].value
print(f"Sales value from B2: {sales_value}")
print(f"Type of the value: {type(sales_value)}") # This will be a float or int
# Loop through rows to get all sales data
# The `iter_rows` method is great for this
# min_row=2, max_row=4 to skip the header
# values_only=True gives you the values directly, not the cell objects
for row in sheet.iter_rows(min_row=2, max_row=4, values_only=True):
    product = row[0]
    sales = row[1]
    print(f"Product: {product}, Sales: {sales}")
# Close the workbook (good practice)
workbook.close()

Output:

Sales value from B2: 1500.75
Type of the value: <class 'float'>
Product: Apples, Sales: 1500.75
Product: Oranges, Sales: 2200.5
Product: Bananas, Sales: 980.25

Writing Numbers to an Excel File

Now, let's create a new Excel file and write some numbers into it.

from openpyxl import Workbook
# Create a new workbook
workbook = Workbook()
# The workbook starts with a sheet named 'Sheet'. Let's rename it.
sheet = workbook.active
sheet.title = "Financial Summary"
# --- Writing numbers ---
# Write headers
sheet['A1'] = "Item"
sheet['B1'] = "Price"
sheet['C1'] = "Quantity"
sheet['D1'] = "Total"
# Write data (integers and floats)
sheet['A2'] = "Laptop"
sheet['B2'] = 1200.50
sheet['C2'] = 2
sheet['D2'] = sheet['B2'].value * sheet['C2'].value # Calculate and write
sheet['A3'] = "Mouse"
sheet['B3'] = 25.99
sheet['C3'] = 5
sheet['D3'] = sheet['B3'].value * sheet['C3'].value
# Save the workbook
workbook.save('financial_summary.xlsx')
print("New Excel file 'financial_summary.xlsx' created successfully.")

After running this, a new file named financial_summary.xlsx will be created with the following content:

Item Price Quantity Total
Laptop 5 2 0
Mouse 99 5 95

Handling Number Formatting (Crucial!)

By default, openpyxl writes numbers as they are. If you want them to appear formatted in Excel (e.g., as currency, dates, or with thousands separators), you need to use the number_format property of a cell.

Python如何处理Excel中的数字?-图3
(图片来源网络,侵删)

Let's modify the previous example to format the "Price" and "Total" columns as currency.

from openpyxl import Workbook
from openpyxl.styles import numbers
workbook = Workbook()
sheet = workbook.active
sheet.title = "Formatted Financial Summary"
# Write headers
sheet['A1'] = "Item"
sheet['B1'] = "Price"
sheet['C1'] = "Quantity"
sheet['D1'] = "Total"
# Write data
sheet['A2'] = "Laptop"
sheet['B2'] = 1200.50
sheet['C2'] = 2
sheet['D2'] = sheet['B2'].value * sheet['C2'].value
sheet['A3'] = "Mouse"
sheet['B3'] = 25.99
sheet['C3'] = 5
sheet['D3'] = sheet['B3'].value * sheet['C3'].value
# --- Apply Number Formatting ---
# Format 'Price' column (B) and 'Total' column (D) as currency
# '$#,##0.00' is a format code for US Dollar with two decimal places
# See more format codes below the example.
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row, min_col=2, max_col=4):
    for cell in row:
        # Check if the cell contains a number (int or float)
        if isinstance(cell.value, (int, float)):
            cell.number_format = numbers.FORMAT_CURRENCY_USD_SIMPLE # Or use a custom string like '$#,##0.00'
# Save the workbook
workbook.save('formatted_financial_summary.xlsx')
print("Formatted Excel file 'formatted_financial_summary.xlsx' created.")

Now, when you open formatted_financial_summary.xlsx, the "Price" and "Total" columns will show as $1,200.50 and $2,401.00 respectively, even though the underlying cell value is still 5.

Common Number Format Codes

You can use built-in constants from openpyxl.styles.numbers or custom format strings.

Format Type Constant Custom String Example Description
Currency numbers.FORMAT_CURRENCY_USD_SIMPLE '$#,##0.00' $1,200.50
General numbers.FORMAT_GENERAL 'General' Default format
Decimal numbers.FORMAT_NUMBER '#,##0.00' 1,200.50
Percentage numbers.FORMAT_PERCENTAGE '0.00%' 7550 becomes 50%
Date numbers.FORMAT_DATE_YYYYMMDD2 'MM/DD/YYYY' 2025-10-25 becomes 10/25/2025
Integer numbers.FORMAT_NUMBER '#,##0' 1500

Reading Formatted Numbers (Advanced)

If you read a cell that has a number format, cell.value will give you the raw Python number (e.g., 5). To get the formatted string as it appears in Excel, you can use cell.number_format.

from openpyxl import load_workbook
# Use the formatted file from the previous example
workbook = load_workbook('formatted_financial_summary.xlsx')
sheet = workbook.active
# Get the cell with the price of the laptop
cell_b2 = sheet['B2']
print(f"Raw cell value: {cell_b2.value}")  # This will be the number: 1200.5
print(f"Cell number format: {cell_b2.number_format}") # This will be the format string: '$#,##0.00'
print(f"Formatted string (from Excel): {cell_b2.is_date}") # This is false, but for numbers you can format it yourself
# To get the formatted string, you can format it manually in Python
formatted_value = f"{cell_b2.value:,.2f}"
print(f"Manually formatted value: ${formatted_value}") # This gives you $1,200.50
workbook.close()

Summary of Key Functions/Properties

Task Code/Property Description
Load File load_workbook('filename.xlsx') Opens an existing Excel file.
Create File Workbook() Creates a new, blank workbook.
Get Sheet workbook.active or workbook['Sheet Name'] Selects a worksheet to work with.
Read Value sheet['A1'].value Gets the raw value from a cell.
Write Value sheet['A1'] = 123 Sets the raw value of a cell.
Read Data sheet.iter_rows(values_only=True) Efficiently loops through rows to get data.
Format Cell cell.number_format = '$#,##0.00' Sets how a number is displayed in Excel.
Save File workbook.save('filename.xlsx') Saves the workbook to a file.
Close File workbook.close() Closes the workbook (good practice).
分享:
扫描分享到社交APP
上一篇
下一篇