al123
al123

Reputation: 569

excel data from asp

i have made a list of folders from my directory, to show as html.

What i want is to be able to read and write in excel.

now what am strugleing to do is put this code to get it as .xlsx. i have a excel file in my computer and want all the directories to go in that file..

I have been told EPPlus is the best solution. but am not sure how to implement this in the above code so my directories comes in excel rather than html.

any ideas/direction would be really helpful

Upvotes: 0

Views: 180

Answers (1)

bamblack
bamblack

Reputation: 3779

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.

Upvotes: 4

Related Questions