Wachburn
Wachburn

Reputation: 2939

How to write an Excel worksheet to a MemoryStream?

I have this code, but it saves to the file

            Excel.Application app = new Excel.Application();
            app.Workbooks.Add();
            Excel._Worksheet sheet = app.ActiveSheet;
            sheet.Cells[1, "A"] = "login";
            sheet.Cells[1, "B"] = "e-mail";

            int row = 1;
            foreach (ProviderUser u in users)
            {
                row++;
                sheet.Cells[row, "A"] = u.UserName;
                sheet.Cells[row, "A"] = u.Email;
            }

            string pathToSave = Path.Combine(Environment.CurrentDirectory, "users.xlsx");
            sheet.SaveAs(pathToSave);
            app.Quit();

Upvotes: 1

Views: 7321

Answers (1)

Dominic Shaw
Dominic Shaw

Reputation: 11

Do you know the location of the file or do you need to create it using Excel first?

You can easily get the byte array of the file using

var buffer = File.ReadAllBytes(pathToSave)

and then create your memory stream with the byte array:

var stream = new MemoryStream(buffer);

Is that what you mean?

Upvotes: 1

Related Questions