Youmna Habchy
Youmna Habchy

Reputation: 107

Creating multiple sheets of excel from c# using streamwriter

I'm using the streamwriter to create an excel file. but the problem is that I didn't find a way to create multiple sheets and specify their names from c#. Also I wanted to draw a chart on excel using streamwriter. So does anybody have an idea how to do both things using streamwriter and not excel instance?? My code is like this:

String sPath = Environment.GetEnvironmentVariable("TEMP") + "\\Synthese.xls";
FileStream oFile = new FileStream(sPath, FileMode.Create);
StreamWriter oWriter = new StreamWriter(oFile, System.Text.Encoding.UTF8);
oWriter.WriteLine("<table border='1' border-color='#ffffff' style=font-weight:bold;><tr>");
...
oWriter.Close();
oFile.Close();
FileInfo myFile = new FileInfo(sPath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name);
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();

Any help is highly appreciated.

Upvotes: 0

Views: 9994

Answers (1)

dav_i
dav_i

Reputation: 28157

It looks like you're trying to write pseudo-HTML to a xls file and hope it works... I'd be surprised if Excel even opens it.

You are better off using a proper tool for the job.

I suggest looking at EPPlus which allows you to create excel documents in C# with all the features you are describing.

Example lifted from the codeplex site:

FileInfo newFile = new FileInfo(outputDir.FullName + @"\sample6.xlsx");

ExcelPackage pck = new ExcelPackage(newFile);

//Add the Content sheet
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = false;

//Headers
ws.Cells["B1"].Value = "Name";
ws.Cells["C1"].Value = "Size";
ws.Cells["D1"].Value = "Created";
ws.Cells["E1"].Value = "Last modified";
ws.Cells["B1:E1"].Style.Font.Bold = true;

Additionally it is advisable to use using statements when using IDisposable classes such as FileStream:

using (var stream = new FileStream(path, FileMode.Create))
{
    // ... stuff using stream in here
}

Upvotes: 1

Related Questions