使用XLSX文件转换为CSV文件 [英] Converting XLSX file using to a CSV file

查看:223
本文介绍了使用XLSX文件转换为CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将XLSX文件转换为另一个CSV文件. 我已经对如何执行此过程进行了大量研究,但没有找到适合我的方法. 我发现此Github Gist仅将Epplus ExcelPackage转换为CSV文件

I need to convert an XLSX file to another CSV file. I've done a lot of research on how to do this process, but I did not find anything that suited me. I found this Github Gist only Convert an Epplus ExcelPackage to a CSV file

这将返回一个二进制数组.但是显然,它不再起作用了.

That returns an Array of binary. But apparently it does not work any more.

我正在尝试使用LoadFromCollection

    FileInfo novoArquivoCSV = new FileInfo(fbd.SelectedPath);
    var fileInfoCSV = new FileInfo(novoArquivo + "\\" +
                                 nameFile.ToString() + ".csv");


            using (var csv = new ExcelPackage(fileInfoCSV))
        {
            csv.Workbook.Worksheets.Add(nameFile.ToString());
            var worksheetCSV = csv.Workbook.Worksheets[1];

            worksheetCSV.Cells.LoadFromCollection(xlsx.ConvertToCsv());

        }

推荐答案

您链接的代码将读取XLSX工作表,并通过内存流将CSV数据作为字节缓冲区返回.

The code you linked to reads an XLSX sheet and returns the CSV data as a byte buffer through a memory stream.

如果您删除内存流并将路径传递到ConvertToCsv中的目标文件,则可以直接写入文件:

You can write directly to a file instead, if you remove the memory stream and pass the path to the target file in ConvertToCsv :

public static void ConvertToCsv(this ExcelPackage package, string targetFile)
{
        var worksheet = package.Workbook.Worksheets[1];

        var maxColumnNumber = worksheet.Dimension.End.Column;
        var currentRow = new List<string>(maxColumnNumber);
        var totalRowCount = worksheet.Dimension.End.Row;
        var currentRowNum = 1;

        //No need for a memory buffer, writing directly to a file
        //var memory = new MemoryStream();

        using (var writer = new StreamWriter(targetFile,false, Encoding.UTF8))
        {
        //the rest of the code remains the same
        }

        // No buffer returned
        //return memory.ToArray();
}

Encoding.UTF8 确保文件将以带有字节顺序标记的UTF8写入,从而使所有程序都可以理解这是UTF8文件而不是ASCII.否则,程序可能会以ASCII格式读取文件,并在遇到的第一个非ASCII字符处阻塞.

Encoding.UTF8 ensures the file will be written as UTF8 with a Byte Order Mark that allows all programs to understand this is a UTF8 file instead of ASCII. Otherwise, a program could read the file as ASCII and choke on the first non-ASCII character encountered.

这篇关于使用XLSX文件转换为CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆