下面提供使用 Python 和 Perl 两种常用语言的示例代码,来实现将 Excel 文件 (.xlsx) 转换为 CSV 文件。

首先是 Python 的示例代码:

使用 Python 实现 xlsx 转换为 csv:

# 导入所需模块
import pandas as pd

# 读取 Excel 文件并写入 CSV 文件
def convert_xlsx_to_csv(input_file, output_file):
    df = pd.read_excel(input_file)  # 读取 Excel 文件
    df.to_csv(output_file, index=False)  # 写入 CSV 文件

# 指定输入和输出文件名
input_excel_file = "input.xlsx"
output_csv_file = "output.csv"

# 执行转换
convert_xlsx_to_csv(input_excel_file, output_csv_file)

以上是使用 Python 完成 xlsx 转换为 csv 的示例,接下来是使用 Perl 的示例代码:

使用 Perl 实现 xlsx 转换为 csv:

# 导入所需模块
use strict;
use warnings;
use Spreadsheet::ParseXLSX;
use Text::CSV;

# 读取 Excel 文件并写入 CSV 文件
sub convert_xlsx_to_csv {
    my ($input_file, $output_file) = @_;

    my $parser = Spreadsheet::ParseXLSX->new();
    my $workbook = $parser->parse($input_file);

    die "Could not parse $input_file: $!" unless $workbook;

    my $csv = Text::CSV->new({binary => 1});
    open my $fh, ">:encoding(utf8)", $output_file or die "$output_file: $!";

    for my $worksheet ( $workbook->worksheets() ) {
        for my $row (0..$worksheet->maxrow) {
            $csv->combine($worksheet->row($row));
            print $fh $csv->string(), "\n";
        }
    }

    close $fh;
}

# 指定输入和输出文件名
my $input_excel_file = "input.xlsx";
my $output_csv_file = "output.csv";

# 执行转换
convert_xlsx_to_csv($input_excel_file, $output_csv_file);

您可以根据实际情况调整文件名和路径。这两个示例展示了分别使用 Python 和 Perl 实现 xlsx 到 csv 转换的方法。

03-22 18:41