能否提供一个Shell脚本示例,用于将由分号 ';' 分割的CSV文件转换为XLSX格式?
时间: 2024-12-10 14:39:13 浏览: 21
当然可以,这里有一个简单的Shell脚本示例,它使用`csvkit`工具集(如果系统中未安装,需要先安装)来处理CSV文件并将其转换为XLSX格式,然后使用`xlsxwriter`库创建XLSX文件。假设你的CSV文件名是`data.csv`:
```bash
#!/bin/bash
# 安装所需的csvkit库(如果没有安装)
if ! command -v csvcut &> /dev/null; then
echo "Installing csvkit..."
curl -L https://github.com/wireservice/csvkit/releases/download/v1.0.4/csvkit-linux-amd64-v1.0.4.tar.gz | tar xz -C /usr/local/bin && sudo chmod +x /usr/local/bin/csvkit*
fi
# 检查xlsxwriter是否已安装,如果没有则安装
if ! command -v python3-xlsxwriter &> /dev/null; then
echo "Installing xlsxwriter..."
pip3 install xlsxwriter
fi
# 将CSV转换为XLSX
csv_file="data.csv"
xlsx_file="output.xlsx"
echo "Converting CSV to XLSX..."
csvcut "$csv_file" > temp_data.txt
python3 -c "
import csv
from xlsxwriter.workbook import Workbook
with open('temp_data.txt', 'r') as f, open('$xlsx_file', 'w', newline='') as xlsx:
reader = csv.reader(f)
writer = Workbook(xlsx)
worksheet = writer.add_worksheet()
for row_num, row in enumerate(reader):
worksheet.write_row(row_num, 0, row)
writer.close()
" < temp_data.txt
# 删除临时文本文件
rm temp_data.txt
echo "Conversion complete. Output file is $xlsx_file."
阅读全文