This code helps you to convert a datagrid data to excel and also to zip it.
It requires the free ICsharp dll. which you can find it on www.google.com
CODE:
public bool ExceltoZip(DataGrid dgExport, HttpResponse response)
{
try
{
string filename, tmpname, filenamezip;
StringWriter strWriter;
FileStream outputStream;
StringBuilder renderedOutput;
StreamWriter sWriter;
HtmlTextWriter twriter;
tmpname = "tmp_" + DateTime.Now.Millisecond.ToString() + "_" + DateTime.Now.Minute.ToString();
renderedOutput = new StringBuilder();
strWriter = new StringWriter(renderedOutput);
twriter = new HtmlTextWriter(strWriter);
dgExport.RenderControl(twriter);
filename = System.Web.HttpContext.Current.Server.MapPath("") + "\\GeneratedFiles\\" + tmpname + ".xls";
filenamezip = System.Web.HttpContext.Current.Server.MapPath("") + "\\GeneratedFiles\\" + tmpname + ".zip";
outputStream = new FileStream(filename, FileMode.Create);
sWriter = new StreamWriter(outputStream);
sWriter.Write(renderedOutput.ToString());
sWriter.Flush();
sWriter.Close();
ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filename));
FileInfo fi = new FileInfo(filename);
entry.ExternalFileAttributes = (int)fi.Attributes;
entry.Size = fi.Length;
FileStream input = File.OpenRead(filename);
ICSharpCode.SharpZipLib.Zip.ZipOutputStream output = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(filenamezip));
output.PutNextEntry(entry);
byte[] buffer = new byte[input.Length];
int len;
do
{
len = input.Read(buffer, 0, buffer.Length);
if (len > 0)
{
output.Write(buffer, 0, len);
}
} while (!(len == 0));
output.Close();
input.Close();
FileStream outputStream1;
outputStream1 = new FileStream(filenamezip, FileMode.Open, FileAccess.Read);
MemoryStream ms;
ms = new MemoryStream((in
0 comments:
Post a Comment