|
发表于 2024-7-18 13:52:39
|
显示全部楼层
明白了,下面我会提供一个完整的 Python 代码示例,展示如何使用 pandas 和 openpyxl 进行以下操作:
1. 从 CSV 文件读取数据,并允许自定义表头。
2. 对第一列序号进行重新赋值,从 1 开始排序。
3. 设置 A、B、C 三列的宽度为自适应。
4. 为数据区域添加表格框线。
首先,确保你已经安装了 pandas 和 openpyxl 库。如果还没有安装,可以通过以下命令进行安装:
- pip install pandas openpyxl
复制代码
然后使用以下代码:
- import pandas as pd
- from openpyxl import Workbook
- from openpyxl.utils.dataframe import dataframe_to_rows
- from openpyxl.styles import Border, Side
- from openpyxl.utils import get_column_letter
- # 读取 CSV 文件,允许自定义表头
- def read_csv_with_header(file_path, custom_header=None):
- if custom_header is not None:
- df = pd.read_csv(file_path, header=None)
- df.columns = custom_header
- else:
- df = pd.read_csv(file_path)
- return df
- # 示例 CSV 文件路径和自定义表头
- csv_file_path = 'data.csv'
- custom_header = ['A', 'B', 'C'] # 自定义表头
- # 读取 CSV 文件
- df = read_csv_with_header(csv_file_path, custom_header)
- # 添加或重新赋值序号列
- df.insert(0, '序号', range(1, len(df) + 1))
- # 创建一个新的 Excel 工作簿
- wb = Workbook()
- ws = wb.active
- # 将 DataFrame 写入 Excel 工作表
- for r in dataframe_to_rows(df, index=False, header=True):
- ws.append(r)
- # 自适应 A、B、C 三列宽度
- for col in ['A', 'B', 'C']:
- max_length = 0
- column = ws[col]
- for cell in column:
- try:
- if len(str(cell.value)) > max_length:
- max_length = len(cell.value)
- except:
- pass
- adjusted_width = (max_length + 2)
- ws.column_dimensions[col].width = adjusted_width
- # 为表格添加框线
- thin_border = Border(left=Side(style='thin'),
- right=Side(style='thin'),
- top=Side(style='thin'),
- bottom=Side(style='thin'))
- for row in ws.iter_rows(min_row=1, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
- for cell in row:
- cell.border = thin_border
- # 保存 Excel 文件
- excel_file_path = 'output.xlsx'
- wb.save(excel_file_path)
- print(f"Excel 文件已保存到 {excel_file_path}")
复制代码
### 代码解释:
1. **读取 CSV 文件**:定义了 `read_csv_with_header` 函数来读取 CSV 文件,并允许用户传递自定义表头。
2. **序号列重新赋值**:通过 `df.insert` 方法在数据框的第一列插入序号列,序号从 1 开始。
3. **创建 Excel 工作簿**:使用 openpyxl 创建一个新的 Excel 工作簿,并将 DataFrame 写入工作表。
4. **自适应列宽**:遍历 A、B、C 三列,计算每列的最大字符长度并设置相应的列宽。
5. **添加表格框线**:为数据区域添加边框。
6. **保存 Excel 文件**:将最终的 Excel 文件保存到指定路径。
这样,你的 Excel 文件就有了自定义表头、序号列重新排序、自适应宽度以及表格框线。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|