Creating multiple sheets of excel from c# using streamwriter - c#

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.

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
}

Related

How to download SQL data in excel format using asp.net

I'm trying to download my data in excel format . Following code does the work perfectly but format comes out to be corrupted.
Error which I get - The file format and extension don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyways?
On confirming Yes, file opens.
Please have to look at the code and help me understand what change I must make to download my data in (xls 97-2003 excel workbook).
if (dt4.Rows.Count > 0)
{
string filename = "DownloadMobileNoExcel.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt4;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Firstly
Download Open Xml
Download Close Xml Library
import this Namespaces
using System.IO;
using System.Data;
using ClosedXML.Excel;
using System.Configuration;
using System.Data.SqlClient;
try to do that like this
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Customers");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
Mudassar Khan has a nice article regarding that
here

How do I save a word document to my file system instead of printing it out?

In my application I print my div to a word document like this:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=testme.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/doc";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
divExport.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
Instead of opening it on the browser How would I go about saving it to a path? Generally when using ItextSharp I would declare the path and the existing template file.
private static string AppRelativePath_1page = "~/DesktopModules/MyFolder";
private static string AppAbsolutePath_1page = HttpContext.Current.Server.MapPath(AppRelativePath_1page);
In this case there is no existing template file. How would I go about creating this file in my server folder?
Open a StreamWriter, and instead of writing to the Response object, write to your StreamWriter.
you do it by using Streamwriter
using (StreamWriter sw = new StreamWriter(Path))
{
sw.Write(stringWrite.ToString());
}

Error dialog displayed when opening an excel file generated with EPPlus

I am creating an Excel file using the EPPlus library. When I create file and open up the file, the following pop up message shows:
We found a problem with some content in 'ExcelDemo.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes
I am using following code
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells[1, 2].Value = "Excel Download";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Is there problem in my code or is this an Excel issue?
In my case the problem was in calling
package.Save();
and using
Response.BinaryWrite(package.GetAsByteArray());
at the same time.
When you call package.GetAsByteArray() it perfoms following operations internally:
this.Workbook.Save();
this._package.Close();
this._package.Save(this._stream);
So, calling package.Save two times leads to this error when opening in Excel.
At the start, you need to add in a:
Response.Clear();
Then at the end add a
Response.End();
I will share my solution. I am using a template excel file and then create new excel from it.
Receiving the same error. My code was
using (Stream newFileStream = File.Open(this.tempFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
using (Stream originalFile = File.Open(this.initialFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (ExcelPackage excelPackage = new ExcelPackage(newFile, template))
{
// ... Do work here
}
I had to change code to:
FileInfo intialInfo = new FileInfo(this.initialFilePath);
FileInfo tempFileInfo = new FileInfo(this.tempFilePath);
using (ExcelPackage excelPackage = new ExcelPackage(tempFileInfo, intialInfo))
{
//... Do work here
}
Also I am using ASP MVC and the response is:
byte[] result = exporter.GetBytesFromGeneratedExcel();
return this.File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Test.xlsx");
In my case, problem was data table name which I did not set earlier.
Try this one,
dt.TableName = "ExcelSheet1";
I was having this problem because I was writing a string larger than 32,767 characters into a single cell. Excel doesn't like this, but EPPlus won't stop you from doing it.
My code was updated... and was getting the same error.... and I finally found my solution
Original Code:
public static void ExportToExcel(HttpContext ctx, DataTable tbl, string fileName)
{
try
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(fileName);
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
int rowCount = tbl.Rows.Count;
List<int> dateColumns = new List<int>();
foreach (DataColumn d in tbl.Columns)
{
if (d.DataType == typeof(DateTime))
dateColumns.Add(d.Ordinal + 1);
}
CultureInfo info = new CultureInfo(ctx.Session["Language"].ToString());
foreach (int dc in dateColumns)
ws.Cells[2, dc, rowCount + 1, dc].Style.Numberformat.Format = info.DateTimeFormat.ShortDatePattern;
//Write it back to the client
ctx.Response.Clear();
ctx.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xlsx");
ctx.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ctx.Response.Buffer = false;
ctx.Response.BufferOutput = false;
ctx.Response.BinaryWrite(pck.GetAsByteArray());
ctx.Response.End();
}
}
catch (Exception EX)
{
ctx.Response.Write(EX.ToString());
}
}
Code update:
catch (Exception EX)
{
if (!(EX is System.Threading.ThreadAbortException))
{
ctx.Response.Write(EX.ToString());
}
}
IT WORKED!
A solution I came up with was just returning the file object in the controller. The first argument should be the byte array (file), the second argument is the content type, and the last argument is the filename (in my case "report.xlsx").
return File(file, "application/octet-stream", fileName);
Hope this helped.

Exporting Grid Data to Excel and saving it in zip format

Hi i'm working on asp net application. In this I need to Export Grid data to Excel and finally the excel file should be saved as zip file. I don't want to first save Excel file in some location then use zip functionality to fetch that file and convert it into Zip and save it. I want functionality which will directly convert Grid to Excel then Zip then finally saves it. I've seen so many forms and sites but none gave proper answer.
You can do this by dot.net Zip dll And following code will help you
gv.AllowPaging = false;
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/zip";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
// byte[] toBytes = Encoding.ASCII.GetBytes(somestring);
MemoryStream stream = new MemoryStream();
string attachment = sw.ToString();
byte[] data = Encoding.ASCII.GetBytes(attachment);
stream.Write(data, 0, data.Length);
stream.Seek(0, SeekOrigin.Begin); // <-- must do this after writing the stream!
// File.WriteAllBytes(#"D:\Saurabh\Testing\inputpdf\saurabhhtest.xls", stream.GetBuffer());
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddEntry("saurabhtest1.xls", stream);
zipFile.Save(Response.OutputStream);
}

How to write data to excel file and download it in asp.net

i have develop an application for online store in which different store keep there catalog online. but i have to develop an functionality for download there catalog in xls file for that i have my data in datatable which i have to write in dynamically generated xls file and download it.
for that i have try fallowing :
DataTable ProductDetails = sql.ExecuteSelectCommand("SELECT * FROM Products_Details_View WHERE Supp_Id = " + Session["SuppID"].ToString() + " and Is_Available = 1");
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=Catalog.xls");
Response.ContentType = "application/excel";
Response.Write(ProductDetails);
Response.End();
i refer it here
but am not getting any thing
please help to get out of it.
I use the EPPlus package, which you can install via Nuget. It allows you to load data onto an Excel worksheet directly from your datatable, and it includes support for things like formatting on the worksheet (fonts, column widths etc). See their
documentation page here on using it inside a web application.
For your case, I would suggest something like:
DataTable ProductDetails = sql.ExecuteSelectCommand("SELECT * FROM Products_Details_View WHERE Supp_Id = " + Session["SuppID"].ToString() + " and Is_Available = 1");
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1.
//Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(ProductDetails, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ProductDetails.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Try this
string attachment = "attachment; filename=xxxx" + DateTime.Now + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
ProductDetails.RenderControl(htextw);
GridView dg = new GridView(); //Create an empty Gridview to bind to datatable.
dg.AutoGenerateColumns = true;
dg.DataSource = ProductDetails;
dg.DataBind();
dg.RenderControl(htw);
Response.Write(stw.ToString());
stw.Close();
Response.End();

Categories