如何用Python将列表元素写入Excel指定位置的单元格?
Write my_list to Excel Sheet3 Row 22 Columns 13-19
Got it, since you already have your data tucked into my_list, here are two straightforward ways to dump those values into the exact cells you need using the libraries you mentioned:
Using openpyxl (direct cell control)
This is perfect if you want to target specific cells without messing with other data in the workbook:
from openpyxl import load_workbook # First, load your existing Excel file (swap 'your_file.xlsx' with your actual file path) wb = load_workbook('your_file.xlsx') sheet3 = wb['sheet3'] # Grab sheet3 by its name # Your pre-extracted list my_list = [1941533, 1002, 0.0005160870301972719, 8523, 1937, 479367.6439999999] start_col = 13 # Column 13 is 'M' in Excel target_row = 22 # Loop through each item in my_list and write it to the correct cell for index, value in enumerate(my_list): # Column number starts at 13 and increments with each list item sheet3.cell(row=target_row, column=start_col + index, value=value) # Don't forget to save your changes! wb.save('your_file.xlsx')
Using pandas (DataFrame approach)
If you prefer working with DataFrames, this method lets you write the list as a single row directly to the right spot:
import pandas as pd # Use ExcelWriter with mode='a' to append without overwriting the whole sheet with pd.ExcelWriter('your_file.xlsx', mode='a', engine='openpyxl', if_sheet_exists='overlay') as writer: # Turn your list into a 1-row DataFrame df = pd.DataFrame([my_list]) # Write to sheet3: startrow=21 (since pandas uses 0-based indexing), startcol=12 (column 13 is 0-based 12) df.to_excel(writer, sheet_name='sheet3', startrow=21, startcol=12, header=False, index=False)
Quick notes to avoid headaches:
- For pandas, remember that
startrowandstartcolare 0-based. So Excel row 22 becomesstartrow=21, column 13 becomesstartcol=12. - The
if_sheet_exists='overlay'flag ensures we only write to the specified cells, not overwrite the entire sheet. - Make sure the Excel file is closed when you run these scripts—open files can cause permission errors.
内容的提问来源于stack exchange,提问作者satoshi
相关产品推荐
相关产品推荐

