0

I need to convert ExcelPackage to file or memory stream .csv and have no idea how can I do it.

using (var package = new ExcelPackage(newFile))
{
    //data...
    package.Save();
    return // I need convert package to 
           //file or memory stream with extension csv
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Tom Alwson
  • 47
  • 1
  • 5
  • Why what you have found wasn't good enough? Maybe we would spend time to help and at the end we would provide the same. For example this: https://gist.github.com/andrewmurray/b63b7592386cb67124d1 (look at the method `ConvertToCsv`) – Tim Schmelter Oct 30 '18 at 13:09
  • i found it earlier, but that ,method converting only 1 worksheet – Tom Alwson Oct 30 '18 at 13:23
  • So you need a way to use that code but to convert all worksheets? Why you don't tell it and show the code? – Tim Schmelter Oct 30 '18 at 13:31
  • 2
    If that's true you simply need to use a loop instead of the fix `package.Workbook.Worksheets[1]` – Tim Schmelter Oct 30 '18 at 13:38
  • 2
    CSV does not directly support multiple worksheets - so you would need to consider how you intend to implement that. – PaulF Oct 30 '18 at 13:44
  • Have you ever thought about using an OleDb to connect to the file, retrieve the data from each sheet and then convert the data into a CSV file? https://stackoverflow.com/questions/18511576/reading-excel-file-using-oledb-data-provider. https://stackoverflow.com/questions/4959722/c-sharp-datatable-to-csv – Mark Kram Oct 30 '18 at 14:14

1 Answers1

0

I would like to give you just an example of a working solution. Assume that excel worksheets have a header and are in the specified range.

Code below exports data to CSV with the filename of the worksheet.

using (var package = new ExcelPackage(new FileInfo("myBook.xlsx")))
{
    foreach (var worksheet in package.Workbook.Worksheets)
    {
        worksheet
            .Cells["A1:B3"]
            .SaveToText(
                new FileInfo($"{worksheet}.csv"),
                new ExcelOutputTextFormat());
    }
}

As you can imagine, you can do whatever you want, export with or without headers, customize your ranges, export specific worksheets, combine data from all worksheets, and so on. But this is another thing. It really depends on your requirements.

There is also ToText() method, so you can process it further.

Reading and Writing Data

T. Dominik
  • 406
  • 3
  • 13