How do I export data from a GridView to a .txt - c#

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();
}

Related

Write CSV then Save or Edit

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();
}

Data is not being returned in table format on SqlDataReader for download csv file

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();
}

Response,End() giving error

Below is my code. In response.end() this error occurs: "Unable to evaluate expression because the code is optimized or the native frame is on top of the call stake."
try
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".csv");
context.Response.Charset = "";
context.Response.ContentType = "application/text";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < dtCsv.Columns.Count; k++)
{
//add separator
sb.Append(dtCsv.Columns[k].ColumnName + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < dtCsv.Rows.Count; i++)
{
for (int k = 0; k < dtCsv.Columns.Count; k++)
{
//add separator
sb.Append(dtCsv.Rows[i][k].ToString().Replace(",", ";") + ',');
}
//append new line
sb.Append("\r\n");
}
context.Response.Output.Write(sb.ToString());
context.Response.Flush();
context.Response.End();
}
catch (Exception ex)
{
ex.Message.ToString();
}

Export DataTable to Excel and save to local directory

I have below functions that take Data Table and convert to excel and prompt user to download the excel.
May I know how can I change the function so that it is save to my local directory instead of download?
public static void ExportDataTableToExcel(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
string attachment = "attachment; filename=" + name + ".xls";
context.Response.ClearContent();
context.Response.AddHeader("content-disposition", attachment);
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.ContentEncoding = System.Text.Encoding.Unicode;
context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
string tab = "";
foreach (DataColumn dc in table.Columns)
{
context.Response.Write(tab + dc.ColumnName);
tab = "\t";
}
context.Response.Write("\n");
int i;
foreach (DataRow dr in table.Rows)
{
tab = "";
for (i = 0; i < table.Columns.Count; i++)
{
context.Response.Write(tab + "=\"" + dr[i].ToString() + "\"");
tab = "\t";
}
context.Response.Write("\n");
}
context.Response.End();
}
Found and implemented the function
public static bool SaveDataTableToExcel(DataTable table, string savePath)
{
//open file
StreamWriter wr = new StreamWriter(savePath, false, Encoding.Unicode);
try
{
for (int i = 0; i < table.Columns.Count; i++)
{
wr.Write(table.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (table.Rows.Count); i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
if (table.Rows[i][j] != null)
{
wr.Write("=\"" + Convert.ToString(table.Rows[i][j]) + "\"" + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
catch (Exception ex)
{
LogError(ex);
return false;
}
return true;
}

Datatable to csv write to zip download error: because it is being used by another process

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();

Categories