89 lines
3.0 KiB
Python
89 lines
3.0 KiB
Python
#!/usr/bin/env python3
|
|
import csv
|
|
|
|
# Read CSV and create a simple Python script to generate XLSX using xlsxwriter
|
|
csv_file = "数据表.csv"
|
|
xlsx_file = "数据表.xlsx"
|
|
|
|
# Check if xlsxwriter is available
|
|
try:
|
|
import xlsxwriter
|
|
|
|
# Create a workbook and add a worksheet
|
|
workbook = xlsxwriter.Workbook(xlsx_file)
|
|
worksheet = workbook.add_worksheet("数据表")
|
|
|
|
# Add a bold format for headers
|
|
bold = workbook.add_format({"bold": True, "align": "center"})
|
|
center = workbook.add_format({"align": "center"})
|
|
|
|
# Read CSV and write to Excel
|
|
with open(csv_file, "r", encoding="utf-8") as f:
|
|
reader = csv.reader(f)
|
|
for row_idx, row in enumerate(reader):
|
|
for col_idx, value in enumerate(row):
|
|
if row_idx == 0: # Header row
|
|
worksheet.write(row_idx, col_idx, value, bold)
|
|
else:
|
|
# Try to convert to number if possible
|
|
try:
|
|
if value:
|
|
num_value = int(value)
|
|
worksheet.write_number(row_idx, col_idx, num_value, center)
|
|
else:
|
|
worksheet.write(row_idx, col_idx, value)
|
|
except ValueError:
|
|
worksheet.write(row_idx, col_idx, value, center)
|
|
|
|
# Set column widths
|
|
for col in range(10):
|
|
worksheet.set_column(col, col, 15)
|
|
|
|
workbook.close()
|
|
print(f"Excel file created: {xlsx_file}")
|
|
|
|
except ImportError:
|
|
print("xlsxwriter not found, trying openpyxl...")
|
|
try:
|
|
from openpyxl import Workbook
|
|
from openpyxl.styles import Font, Alignment
|
|
|
|
wb = Workbook()
|
|
ws = wb.active
|
|
ws.title = "数据表"
|
|
|
|
# Read CSV and write to Excel
|
|
with open(csv_file, "r", encoding="utf-8") as f:
|
|
reader = csv.reader(f)
|
|
for row_idx, row in enumerate(reader, start=1):
|
|
for col_idx, value in enumerate(row, start=1):
|
|
cell = ws.cell(row=row_idx, column=col_idx)
|
|
|
|
# Try to convert to number
|
|
try:
|
|
if value:
|
|
cell.value = int(value)
|
|
else:
|
|
cell.value = value
|
|
except ValueError:
|
|
cell.value = value
|
|
|
|
# Format header row
|
|
if row_idx == 1:
|
|
cell.font = Font(bold=True)
|
|
cell.alignment = Alignment(horizontal="center")
|
|
else:
|
|
cell.alignment = Alignment(horizontal="center")
|
|
|
|
# Set column widths
|
|
for col in range(1, 11):
|
|
ws.column_dimensions[chr(64 + col)].width = 15
|
|
|
|
wb.save(xlsx_file)
|
|
print(f"Excel file created: {xlsx_file}")
|
|
|
|
except ImportError:
|
|
print("Neither xlsxwriter nor openpyxl is available.")
|
|
print("CSV file has been created: 数据表.csv")
|
|
print("You can manually convert it to Excel format.")
|