I have a problem. I'm creating a CSV in runtime, then giving the user the ability to save it or open it, but it does not do anything to me, what am I doing wrong? Can someone help me?
public void WriteToCSV(List<mifid2_vpc_monitored_detail_view> list, string filename)
{
string attachment = "attachment; filename=" + filename;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
WriteHeader();
StringBuilder csv = new StringBuilder();
string _uti, _counterparty;
DateTime _maturity, _date;
decimal _volume;
var newLine = "";
for (int i = 0; i < list.Count; i++)
{
if (list[i].uti_cd == null) _uti = "-"; else _uti = list[i].uti_cd;
if (list[i].namecounterparty == null) _counterparty = "-"; else _counterparty = list[i].namecounterparty;
if (list[i].maturity == null) _maturity = DateTime.MinValue.Date; else _maturity = list[i].maturity;
if (list[i].contract_volume == 0) _volume = 0; else _volume = list[i].contract_volume;
if (list[i].evaluation_date == null) _date = DateTime.MinValue.Date; else _date = list[i].evaluation_date;
newLine = string.Format("{0},{1},{2},{3},{4}", _uti, _counterparty, _maturity, _volume, _date);
csv.AppendLine(newLine);
}
HttpContext.Current.Response.Write(csv.ToString());
HttpContext.Current.Response.End();
}
private void WriteHeader()
{
string columnNames = "UTI code, Counterparty, Maturity, Volume, Evaluation Date";
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}
Code works fine for me. But browser downloads file without extension.
Does filename contains file extension?
If not, try this
string attachment = "attachment; filename=" + filename + ".csv";
I still do not understand where the problem may be, I tried different solutions, then I found an example on the web that works through a demo, but that once I implement it, it does not work, it could be that I work with sharepoint 2013 and that the button that refers to the export is in a webpart?
Code:
HttpResponse Response = HttpContext.Current.Response;
string csv = string.Empty;
csv += "UTI code, Counterparty, Maturity, Volume, Evaluation Date";
csv += "\r\n";
string _uti, _counterparty;
DateTime _maturity, _date;
decimal _volume;
for (int i = 0; i < list.Count; i++)
{
if (list[i].uti_cd == null) _uti = "-"; else _uti = list[i].uti_cd;
if (list[i].namecounterparty == null) _counterparty = "-"; else _counterparty = list[i].namecounterparty;
if (list[i].maturity == null) _maturity = DateTime.MinValue.Date; else _maturity = list[i].maturity;
if (list[i].contract_volume == 0) _volume = 0; else _volume = list[i].contract_volume;
if (list[i].evaluation_date == null) _date = DateTime.MinValue.Date; else _date = list[i].evaluation_date;
csv += _uti + ",";
csv += _counterparty + ",";
csv += _maturity + ",";
csv += _volume + ",";
csv += _date;
csv += "\r\n";
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
This should help:
public void WriteToCSV(List<mifid2_vpc_monitored_detail_view> list, string filename)
{
string attachment = "attachment; filename=" + filename;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
WriteHeader();
StringBuilder csv = new StringBuilder();
string _uti, _counterparty;
DateTime _maturity, _date;
decimal _volume;
var newLine = "";
for (int i = 0; i < list.Count; i++)
{
if (list[i].uti_cd == null) _uti = "-"; else _uti = list[i].uti_cd;
if (list[i].namecounterparty == null) _counterparty = "-"; else _counterparty = list[i].namecounterparty;
if (list[i].maturity == null) _maturity = DateTime.MinValue.Date; else _maturity = list[i].maturity;
if (list[i].contract_volume == 0) _volume = 0; else _volume = list[i].contract_volume;
if (list[i].evaluation_date == null) _date = DateTime.MinValue.Date; else _date = list[i].evaluation_date;
newLine = string.Format("{0},{1},{2},{3},{4}", _uti, _counterparty, _maturity, _volume, _date);
csv.AppendLine(newLine);
}
MemoryStream mstream = new MemoryStream();
StreamWriter sw = new StreamWriter(mstream);
sw.Write(csv);
sw.Flush();
sw.Close();
byte[] byteArray = mstream.ToArray();
mstream.Flush();
mstream.Close();
HttpContext.Current.Response.BinaryWrite(byteArray);
HttpContext.Current.Response.End();
}
Related
I need to get the content inside each page of a crystal report viewer and export it to a pdf file so that each page becomes a separate pdf and need to zip them.
Now i'm using DotNetZip dll for this.That's fine.
The issue is that i need to get contents of each page.Please Help..Below is few lines of code
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=Reports.zip");
int i = 1;
int PageCount = report.FormatEngine.GetLastPageNumber(new
CrystalDecisions.Shared.ReportPageRequestContext());
if(PageCount >= 1){
using (ZipFile zip = new ZipFile())
{
for (i = 1; i <= PageCount; i++){
var re = report.ExportToStream(ExportFormatType.PortableDocFormat);
string Name = "Page" + i + ".pdf";
zip.AddEntry(Name, re);
}
zip.Save(Response.OutputStream);
}
}
Finally i found the answer!!..It may help someone in future.
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=Reports.zip");
int PageCount = report.FormatEngine.GetLastPageNumber(new
CrystalDecisions.Shared.ReportPageRequestContext());
if (PageCount >= 1)
{
using (ZipFile zip = new ZipFile())
{
for (int i = 1; i <= PageCount; i++)
{
PdfRtfWordFormatOptions pdfRtfWordOpts = ExportOptions.CreatePdfRtfWordFormatOptions();
DiskFileDestinationOptions destinationOpts = ExportOptions.CreateDiskFileDestinationOptions();
ExportRequestContext req = new ExportRequestContext();
pdfRtfWordOpts.FirstPageNumber = i;
pdfRtfWordOpts.LastPageNumber = i;
pdfRtfWordOpts.UsePageRange = true;
ExportOptions CrExportOptions = report.ExportOptions;
{
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.FormatOptions = pdfRtfWordOpts;
req.ExportInfo = CrExportOptions;
}
Stream s = report.FormatEngine.ExportToStream(req);
string Name = "Page" + i + ".pdf";
zip.AddEntry(Name, s);
}
zip.Save(Response.OutputStream);
}
}
I'm working on a C# asp.net project and can't seem to get the "exporting to a .txt file from a grid view" to work.
protected void ExportGridToText() {
BindGridView();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
StringBuilder Rowbind = new StringBuilder();
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=GlogData.txt");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Cache.SetCacheability(HttpCacheability.NoCache);
gvLog.DataBind();
for (int i = 2; i < gvLog.Columns.Count; i++)
{
Rowbind.Append("\"" + gvLog.Columns[i].HeaderText + "\"" + ',');
}
Rowbind.Append("\n");
for (int j = 0; j < gvLog.Rows.Count; j++)
{
for (int k = 0; k < gvLog.Columns.Count; k++)
{
Rowbind.Append("\"" + gvLog.Rows[j].Cells[k].Text + "\"" + ',');
Rowbind.Replace("<", "<");
Rowbind.Replace(">", ">");
}
Rowbind.Append("\n");
}
gvLog.AllowPaging = false;
Response.Output.Write(Rowbind.ToString());
Response.Flush();
Response.End();
}
Evrytime I run the code I get a error message:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed
Why is it giving me this error?
How do I fix it?
Is it possible to get the data from the source... This is under the get Button that populates the GridView:
protected void GetLogBtn_Click(object sender, EventArgs e)
{
string sBeginDate = BeginDate.Text;
string sEndDate = EndDate.Text;
JObject vResultJson = new JObject();
FKWebCmdTrans cmdTrans = new FKWebCmdTrans();
DateTime dtBegin, dtEnd;
if (sBeginDate.Length > 0)
{
try
{
dtBegin = Convert.ToDateTime(sBeginDate);
sBeginDate = FKWebTools.GetFKTimeString14(dtBegin);
vResultJson.Add("begin_time", sBeginDate);
}
catch
{
BeginDate.Text = "";
}
}
if (sEndDate.Length > 0)
{
try
{
dtEnd = Convert.ToDateTime(sEndDate);
sEndDate = FKWebTools.GetFKTimeString14(dtEnd);
vResultJson.Add("end_time", sEndDate);
}
catch
{
EndDate.Text = "";
}
}
try
{
string sFinal = vResultJson.ToString(Formatting.None);
byte[] strParam = new byte[0];
cmdTrans.CreateBSCommBufferFromString(sFinal, out strParam);
mTransIdTxt.Text = FKWebTools.MakeCmd(msqlConn, "GET_LOG_DATA", mDevId, strParam);
Session["operation"] = GET_LOG_DATA;
GetLogBtn.Enabled = false;
ClearBtn.Enabled = false;
Timer.Enabled = true;
}
catch (Exception ex)
{
StatusTxt.Text = "Fail! Get Log Data! " + ex.ToString();
}
}
This is under the BindGridView:
private void BindGridView()
{
try
{
string mTransid = mTransIdTxt.Text;
string strSelectCmd = "SELECT COUNT(*) FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlCommand sqlCmd = new SqlCommand(strSelectCmd, msqlConn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
if (sqlReader.HasRows)
{
if (sqlReader.Read())
nCount = sqlReader.GetInt32(0);
}
sqlReader.Close();
sqlCmd.Dispose();
{
DataSet dsLog = new DataSet();
strSelectCmd = "SELECT * FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, msqlConn);
// conn.Open();
da.Fill(dsLog, "tbl_fkcmd_trans_cmd_result_log_data");
DataView dvLog = dsLog.Tables["tbl_fkcmd_trans_cmd_result_log_data"].DefaultView;
gvLog.DataSource = dvLog;
gvLog.DataBind();
StatusTxt.Text = " Total Count : " + Convert.ToString(nCount) + " Current Time :" + DateTime.Now.ToString("HH:mm:ss tt");
}
}
catch (Exception ex)
{
StatusTxt.Text = ex.ToString();
}
}
I hope this helps
Thanks in advance
Following Code is For Excel Mainly...but its successfully converting gridview to .txt file just need a little workaround..
public void ExportToExcel(System.Web.UI.WebControls.GridView controlname, string sheetname)
{
HttpContext context = HttpContext.Current;
context.Response.ClearContent();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".txt"));
context.Response.ContentType = "application/text";
// context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".xls"));
// context.Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//Change the Header Row back to white color
controlname.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < controlname.HeaderRow.Cells.Count; i++)
{
controlname.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in controlname.Rows)
{
gvrow.BackColor = Color.White;
if (j <= controlname.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
controlname.RenderControl(htw);
context.Response.Write(sw.ToString());
context.Response.End();
}
Here is the table structure:
enter image description here
Here is the code:
protected void Write_CSV_From_Recordset2(SqlDataReader oDataReader)
{
StringBuilder builder = new StringBuilder();
List<string> columnNames = new List<string>();
List<string> rows = new List<string>();
for (int i = 0; i < oDataReader.FieldCount; i++)
{
string tmpColumnName = oDataReader.GetName(i);
columnNames.Add(tmpColumnName);
}
builder.Append(string.Join(",", columnNames.ToArray())).Append("\n");
List<string> currentRow = new List<string>();
while (oDataReader.Read())
{
////base.WriteLog(oDataReader.FieldCount + "fieldcount");
for (int i = 0; i < oDataReader.FieldCount; i++)
{
object item = oDataReader[i];
currentRow.Add(item.ToString());
}
}
//builder.Append(string.Join("\n", rows.ToArray())).Append("\n");
rows.Add(string.Join(",", currentRow.ToArray()));
builder.Append(string.Join(",", rows.ToArray())).Append("\n");
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=pretestscore.csv");
Response.Write(builder.ToString());
Response.End();
}
The problem is that while output is begin returned, the
while (oDataReader.Read())
function the value are being returned just like
281063,70,7091,85,TEST,200,test,NULL
How to get actually data from the table?
Where is the mistake in my code?
Any suggestions?
protected void Write_CSV_From_Recordset2(SqlDataReader oDataReader)
{
string strCSV = string.Empty;
for (int i = 0; i < oDataReader.FieldCount; i++)
{
string tmpColumnName = oDataReader.GetName(i);
strCSV += tmpColumnName + ',';
}
strCSV += "\r\n";
while (oDataReader.Read())
{
for (int i = 0; i < oDataReader.FieldCount; i++)
{
object item = oDataReader[i];
strCSV += item.ToString().Replace(",", ";") + ',';
}
strCSV += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=pretestscore.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(strCSV);
Response.Flush();
Response.End();
}
You can directly write code with comma separated with for loop or while loop.
You can refer this code and you will get idea
string s;
while (reader.Read())
{
if(!String.IsNullOrEmpty(s)){
s += ", ";
}
s += reader["name"].ToString();
}
In thst code i have us two database tabele and fetch data in datatable then write all the data in the csv files with help of stream writer then add both the file in a folder and download in a zip form but sometimes its shows an error The process cannot access the file 'xxxxx.zip' because it is being used by another process.
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
//Work Detail
blExportToExcel obj = new blExportToExcel();
System.Data.DataTable dtTechSanc = blDbFunction.GetTechSanc(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
dtTechSanc.Columns["Id"].ColumnName = "WorkCode";
dtTechSanc.Columns["TSId"].ColumnName = "Id";
string filenamezip = "ZipFile\\TechSancRevision_" + DateTime.Now.ToString().Replace(":", "-").Replace("/", "-") + ".zip";
string strPathAndQuery = HttpContext.Current.Request.PhysicalApplicationPath;
string paths = strPathAndQuery + filenamezip;
ZipFile z = ZipFile.Create(paths);
z.BeginUpdate();
if (dtTechSanc.Rows.Count > 0)
{
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "TechSancRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtTechSanc.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtTechSanc.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtTechSanc.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
}
//Fund Allocation
System.Data.DataTable dtFA = blDbFunction.GetFundAllocationTS(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
if (dtFA.Rows.Count > 0)
{
z.BeginUpdate();
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "FundsAllocationRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
dtFA.Columns["FAId"].ColumnName = "Id";
dtFA.Columns["WorkId"].ColumnName = "WorkCode";
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtFA.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtFA.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtFA.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
z.Close();
}
System.IO.FileInfo file = new System.IO.FileInfo(paths);
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + Path.GetFileName(paths));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);/// error shows here
Response.End();
}
}
I am not sure this will help you or not but i am transmitting zip using below code , please try it. It works perfectly and in use from past 2 years.
Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test.zip")
Response.TransmitFile(#"C:\Test.zip");
Response.Flush();
// Prevents any other content from being sent to the browser
Response.SuppressContent = true;
// Directs the thread to finish, bypassing additional processing
HttpContext.Current.ApplicationInstance.CompleteRequest();
I am using VS 2008,C#.net,asp.net.
I am exporting the data to excel 2003.
The exported excel is of the type .xls in IE and Chrome.
But it is not .xls type in mozilla.When open that file, it is asking which program you want to open?
What is the reason?
the program is mentioned below.
## Heading ##
private void ExportDataSetToExcel()
{
try
{
DataSet Ds = new DataSet();
DataTable DT = new DataTable();
string param = hidType.Get("Type").ToString();
string[] codes = param.Split('.');
if (codes.Length == 1)
FillGrid(Convert.ToString(param));
else
FillDrillDownGrid(codes[1], codes[0]);
if (hidType.Get("Type").ToString() == "2")
{
DT.Columns.Add("<b>Sub Group Code</b>");
DT.Columns.Add("<b>Account Sub Group</b>");
}
else if (hidType.Get("Type").ToString() == "3")
{
DT.Columns.Add("<b>Group Code</b>");
DT.Columns.Add("<b>Account Group</b>");
}
else
{
DT.Columns.Add("<b>Acc.Head Code</b>");
DT.Columns.Add("<b>Account Head</b>");
}
DT.Columns.Add("<b>Debit</b>");
DT.Columns.Add("<b>Credit</b>");
for (int j = 0; j < grdTrialBal.VisibleRowCount; j++)
{
DataRow DR;
DR = DT.NewRow();
if (hidType.Get("Type").ToString() == "2")
{
DR["<b>Sub Group Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Sub Group</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
else if (hidType.Get("Type").ToString() == "3")
{
DR["<b>Group Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Group</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
else
{
DR["<b>Acc.Head Code</b>"] = grdTrialBal.GetRowValues(j, "ahdUserCode");
DR["<b>Account Head</b>"] = grdTrialBal.GetRowValues(j, "ahdname");
}
if (Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt")) != 0)
{
DR["<b>Debit</b>"] = Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt"));
}
if (Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt")) != 0)
{
DR["<b>Credit</b>"] = Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt"));
}
CrAmount = CrAmount + Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdCrAmt"));
DrAmount = DrAmount + Convert.ToDecimal(grdTrialBal.GetRowValues(j, "trnAhdDrAmt"));
DT.Rows.Add(DR);
}
DataRow Dr1;
Dr1 = DT.NewRow();
if (hidType.Get("Type").ToString() == "2")
{
Dr1["<b>Sub Group Code</b>"] = "";
Dr1["<b>Account Sub Group</b>"] = "<b>Total</b>";
}
else if (hidType.Get("Type").ToString() == "3")
{
Dr1["<b>Group Code</b>"] = "";
Dr1["<b>Account Group</b>"] = "<b>Total</b>";
}
else
{
Dr1["<b>Acc.Head Code</b>"] = "";
Dr1["<b>Account Head</b>"] = "<b>Total</b>";
}
Dr1["<b>Debit</b>"] = "<b>" + DrAmount.ToString("#0.#0") + "</b>";
Dr1["<b>Credit</b>"] = "<b>" + CrAmount.ToString("#0.#0") + "</b>";
DT.Rows.Add(Dr1);
DataGrid dg = new DataGrid();
dg.DataSource = DT;
dg.DataBind();
String strFileName = "Trial Balance Account Group Wise.xls";
if (hidType.Get("Type").ToString() == "2")
{
strFileName = "Trial Balance Account Sub Group Wise.xls";
}
else if (hidType.Get("Type").ToString() == "3")
{
strFileName = "Trial Balance Account Group Wise.xls";
}
else
{
strFileName = "Trial Balance Account Head Wise.xls";
}
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
CommonFunctions cf = new CommonFunctions();
String[] aTo = mskToDate1.Text.Split(new[] { '/', '-' });
String dTo;
dTo = aTo[0] + "/" + cf.getMonthName(Convert.ToInt32(aTo[1])) + "/" + aTo[2];
if (hidType.Get("Type").ToString() == "2")
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Sub Group Wise - As on :" + dTo + " </font></u></b>");
}
else if (hidType.Get("Type").ToString() == "3")
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Group Wise - As on :" + dTo + " </font></u></b>");
}
else
{
htw.WriteLine("<b><u><font size='5'>" + "Trial Balance - Account Head Wise - As on : " + dTo + " </font></u></b>");
}
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
dg = null;
dg.Dispose();
}
catch (Exception ex)
{
}
}
set filename in double quotes
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + strFileName+ "\"");