If you want to go the route of EPPlus, first thing you need to do is add the EPPlus package to your solution. This can be achieved by doing one of the following:
- Opening up NuGet, searching for EPPlus in the gallery and installing it
- Opening up your Package Manager Console and typing
Install-Package EPPlus
- Downloading the dll file and manually adding a reference to it in your project.
Then, in your code:
using OfficeOpenXml;
using System.IO;
using System.Linq;
namespace TestConsole {
class Program {
static void Main(string[] args) {
string[] directoryList = System.IO.Directory.GetDirectories(@"C:\Users\bblack\Temp\TestDirectories\");
using (Stream file = new FileStream(@"C:\Users\bblack\Temp\testexcelfile.xlsx", FileMode.Create))
using (ExcelPackage xl = new ExcelPackage(file)) {
ExcelWorksheet sheet = xl.Workbook.Worksheets.Add("Sheet1");
for (int i = 1; i < directoryList.Count(); i++)
sheet.Cells[i, 1].Value = directoryList[i];
xl.Save();
}
}
}
}
This
- Gets all the directories in the address provided to it.
- Creates a new
FileStream
where you want your Excel file to be
- Creates a new
ExcelPackage
based off of the FileStream
- Adds a new worksheet (there are zero by default) to the workbook in the
ExcelPackage
- Iterates through
directoryList
, and for each string in there puts the value in a new cell
it is important to note, that worksheet cell indexes are not zero-based, they start with a base index of 1
edit Woops, forgot to close the stream, use this updated answer.