项目要求
- 能够自动导入excel数据
具体要求如下: - 1) 文件名称是该文件的名称和T组成,比如文件名称是000004.csv,那么他的表名是 T000004
2) 不能排除文件名是中文的情况,但是可以排除文件名称不包含特殊字符,是直接可以用来做表名名称
3)字段名称要求是excel的第一行,可以是中文。
4)要求表,数据库,字段都是utf8格式
5)数据库我们统一使用名称为 excel,用户名是excel,密码是123456
解决思路
寻找xls2csv的插件,就是linux下直接可以运用的。
yum provides xls2csv
直接在cn.bing.com搜索,关键字是 linux .excel,csv,yum
这个不能使用放弃
找到ssconvert 可以转换xlsx 到csv文件
根据安装步骤
首先安装 ssconvert的yum仓库
wget http://repo.iotti.biz/CentOS/7/noarch/lux-release-7-1.noarch.rpm
rpm -ivh http://repo.iotti.biz/CentOS/7/noarch/lux-release-7-1.noarch.rpm
yum install -y gnumeric
- 如果出现类似下面的错误
请先安装yum -y install epel-release
然后我们直接通过ssconvert命令进行
语法为:
ssconvert xlsxfile csvfiile
ssconvert ../zhuanye.xlsx zhuanye.csv
测试成功! 如果有很多的csv文件,那么我们就需要写shell脚本处理了。
自动转换指定目录下的所有xlsx文件到csv的文件的脚本如下
#!/bin/bash
#be sure the ssconvert && gnumberic is installed
#the program usage is : excel2csv input_dir output_dir
#if the output_dir is empty, use the input_dir instead.
input_dir=$1
output_dir=$2
if [ $# -lt 1 ] ; then
echo "please give the input dir "
exit 2
fi
if [ $# -eq 1 ] ; then
output_dir=$1
fi
if [ -d $input_dir -a -x $input_dir ] ; then
for excel in $input_dir/*.xlsx $input_dir/*.xls
do
ssconvert $excel ${excel}.csv 2>/dev/null
done
else
echo "$input_dir is not a directory or has no permission"
exit 1
fi
按照要求创建数据库
直接写代码
mysql <<EOF
create database excel charset utf8;
EOF
create user excel@'%' identified by '123456';
grant all privileges on excel.* to excel@'%';
flush privileges;
创建表,需要shell根据csv的格式去生成
测试
手工测试
手工功能测试又叫黑盒测试,我们给出输入,检验输出,不涉及到中间软件的运行过程的检查。
测试过程需要首先知道输入文件的的总行数以检查核对。
目前我们的文件,专业列表的excel表是739条记录,测试的那个文件总共是3条记录。
我们需要手工做数据库中进行测试,进行验证
自动化测试
验收脚本
#!/bin/bash
# Variables to store conversion counts
success_count=0
failed_count=0
failed_filenames=""
# Loop through all XLS and XLSX files in the current directory
for file in *.xls *.xlsx; do
# Check if the file is a valid XLS or XLSX file
if [[ -f "$file" && "$file" =~ \.(xls|xlsx)$ ]]; then
# Generate the output CSV filename
csv_filename="${file%.*}.csv"
# Convert XLS or XLSX to CSV
if libreoffice --headless --convert-to csv "$file" --outdir . >/dev/null 2>&1; then
# Check if the converted CSV file exists and has content
if [[ -f "$csv_filename" && -s "$csv_filename" ]]; then
echo "Converted: $file"
((success_count++))
else
echo "Failed to convert: $file"
((failed_count++))
failed_filenames+=" $file"
fi
else
echo "Failed to convert: $file"
((failed_count++))
failed_filenames+=" $file"
fi
fi
done
# Print the conversion summary
echo ""
echo "Total Conversion success count: $success_count"
echo "Total conversion failed count: $failed_count"
# Print the failed filenames, if any
if [ "$failed_count" -gt 0 ]; then
echo "Conversion failed filenames:$failed_filenames"
fi
作者:严锋 创建时间:2023-09-19 09:20
最后编辑:严锋 更新时间:2025-05-22 13:03
最后编辑:严锋 更新时间:2025-05-22 13:03