导出列至.csv:解决超15位数字单元格末尾补零问题
问题:保留HTML导出文件中ROUND_ID列的完整数字(避免Excel自动截断)
我是Python编程新手,目前需要解决以下问题:从HTML文件提取游戏提供商及网站信息并导出为文件时,需让ROUND_ID列的超15位原始数字完整保留(最终要交付Excel格式给专业团队)。但Excel打开CSV时会把该列末尾数字改为0,临时方案是给单元格加双引号,但对方需要手动去除;尝试过将列转为文本格式但未成功,求永久解决办法。
现有代码
import csv from bs4 import BeautifulSoup import pandas as pd import os # Set the directory path containing the HTML files directory = 'C:/Users/gusta/Downloads/HTML/' # Create an empty list to store the extracted data filtered_data = [] # Step 1: Loop through each HTML file in the directory for filename in os.listdir(directory): if filename.endswith('.html'): # Read the HTML file file_path = os.path.join(directory, filename) with open(file_path, 'r') as file: html_content = file.read() # Parsing the HTML content soup = BeautifulSoup(html_content, 'html.parser') # Filtering the data data_rows = soup.find_all('tr') # Find all table rows for row in data_rows[1:]: # Skip the header row cells = row.find_all('td') # Handle variations in table structure if len(cells) >= 13: trader_id = cells[3].text.strip() # Extract trader ID from the fourth column name = cells[5].text.strip() # Extract name from the sixth column # Apply desired filters (e.g., trader ID and name) if trader_id == '513' and name == 'PG Soft': # Extract other required columns here collected_data = [ cells[0].text.strip(), cells[1].text.strip(), cells[2].text.strip(), trader_id, cells[4].text.strip(), name, cells[6].text.strip(), cells[7].text.strip(), cells[8].text.strip(), cells[9].text.strip(), cells[10].text.strip(), cells[11].text.strip(), cells[12].text.strip() ] # Convert ROUND_ID to a string surrounded by quotes collected_data[7] = f'"{collected_data[7]}"' # Append the collected_data list to filtered_data filtered_data.append(collected_data) else: print("Unexpected table structure. Skipping row...") # Generating a single DataFrame from all the extracted data df = pd.DataFrame(filtered_data, columns=[ 'CUSTOMER_BET_ID', 'CUSTOMER_CODE', 'USERNAME', 'TRADER_ID', 'TRADER_NAME', 'NAME', 'UID_', 'ROUND_ID', 'PLAYED_DATE', 'S', 'CSN_GAME_ID', 'PLAYED_AMOUNT_FROM_BALANCE', 'GAME_NAME' ]) # Save the DataFrame to a single CSV file with a semicolon (;) as the delimiter output_file = 'output.csv' df.to_csv(output_file, index=False, quoting=csv.QUOTE_NONNUMERIC, quotechar='"', sep=';') print(f'Data extraction and spreadsheet generation completed. Output saved to {output_file}.')
已尝试方案
- 给ROUND_ID添加前后双引号作为临时方案,但需手动去除引号;
- 尝试将列格式设为文本,脚本执行后无效。
解决方案
方法1:优化CSV导出,让Excel自动识别为文本
这种方法不用改变交付格式(依然用CSV),通过给ROUND_ID添加隐藏前缀让Excel识别为文本:
- 删除代码中手动给ROUND_ID加引号的行:
collected_data[7] = f'"{collected_data[7]}"' - 在生成DataFrame后,给ROUND_ID列添加英文单引号前缀(Excel会隐藏该前缀,仅显示完整数字):
df['ROUND_ID'] = "'" + df['ROUND_ID'].astype(str) - 修改
to_csv的参数,避免额外加引号:df.to_csv(output_file, index=False, quoting=csv.QUOTE_MINIMAL, sep=';')
方法2:直接导出为Excel文件(推荐)
直接导出xlsx格式可以直接指定列的文本格式,彻底避免Excel的自动转换问题:
- 先安装依赖库:
pip install openpyxl - 替换原代码中的导出部分为以下内容:
这样导出的Excel文件打开后,ROUND_ID列直接以文本格式显示完整数字,无需任何手动操作。output_file = 'output.xlsx' from openpyxl.styles import numbers with pd.ExcelWriter(output_file, engine='openpyxl') as writer: df.to_excel(writer, index=False) # 获取工作表对象 worksheet = writer.sheets['Sheet1'] # 设置ROUND_ID列(第8列,对应字母H)为文本格式 worksheet.column_dimensions['H'].number_format = '@' print(f'Data extraction completed. Output saved to {output_file}.')
内容的提问来源于stack exchange,提问作者GutoX
相关产品推荐
相关产品推荐

