如何用Python从Excel生成含指定列(Id、Price)的CSV文件
Solution to Export Only "Id" and "Price" Columns from Excel to CSV
Got it, let's tweak your code to only export the specific columns you need. Here's a practical, robust fix that handles common edge cases:
Step 1: Locate Target Column Indices
First, we need to find exactly which positions (indices) the "Id" and "Price" headers occupy in your Excel sheet. This lets us target those columns specifically, even if they're out of order or buried among other columns.
Step 2: Filter Rows & Write to CSV
Once we have the indices, we'll extract only those column values for every row (including the header) and write them to your CSV file.
Here's the modified code:
import csv # Assume `sh` is your already loaded Excel worksheet object csv_file_path = "your_output.csv" # Replace with your actual file path # 1. Get header row and find indices for our target columns header_row = sh.row_values(0) # Adjust the index if your header isn't in the first row (e.g., 1 for second row) try: id_col_index = header_row.index("Id") price_col_index = header_row.index("Price") except ValueError as err: print(f"Oops! Missing required column: {err}") exit() # 2. Write filtered data to CSV (using `with` auto-closes the file) with open(csv_file_path, 'w+', newline='') as csv_file: wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL) # Write the filtered header first wr.writerow(["Id", "Price"]) # Iterate through data rows (skip the header row) for row_num in range(1, sh.nrows): # Use xrange instead of range if you're on Python 2 full_row = sh.row_values(row_num) # Extract only the columns we care about filtered_row = [full_row[id_col_index], full_row[price_col_index]] wr.writerow(filtered_row)
Key Tips for Reliability:
- Auto-close File: Using
with open(...)ensures the file is properly closed after writing, avoiding resource leaks (no need for manualcsv_file.close()). - Case Insensitivity (Optional): If your Excel headers might have inconsistent casing (e.g., "ID" or "price"), make the lookup case-insensitive:
header_lower = [col.lower() for col in header_row] id_col_index = header_lower.index("id") price_col_index = header_lower.index("price") - Python Version: If you're still using Python 2, keep
xrangeinstead ofrange(Python 3 removedxrangeand updatedrangeto behave like it). - Header Position: If your header isn't in the first row (index 0), adjust the
sh.row_values(0)parameter to match the correct row number.
内容的提问来源于stack exchange,提问作者Newton8989
相关产品推荐
相关产品推荐

