Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Converting XLSX file using to a CSV file

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.

I'm trying to load Array using 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());

        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...