How To Save Gridview Into Csv File With Arabic Letters? - c#

I Have A gridView with data contain Arabic letters On My website When I Export To Csv File
on localhost It works Fine when i purplish on server the Arabic letters appear like ????????
where the problem
this is my code
protected void btn_SaveCSV_Click(object sender, EventArgs e)
{
// Response.Clear();
HttpContext.Current.Response.Clear();
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
//Response.ContentType = "application/text";
Response.ContentType = "text/csv; charset-UTF-8";
Response.ContentEncoding = System.Text.Encoding.Default;
Grid_offlineMessages.AllowPaging = false;
FillGrid();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < Grid_offlineMessages.Columns.Count; k++)
{
//add separator
sb.Append(Grid_offlineMessages.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < Grid_offlineMessages.Rows.Count; i++)
{
for (int k = 0; k < Grid_offlineMessages.Columns.Count; k++)
{
//add separator
sb.Append(Grid_offlineMessages.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}

Try setting the encoding to UTF-8 like this:
Response.ContentEncoding = System.Text.Encoding.UTF8;

Related

GridView is not being exported into Excel file

I read a few posts around here but couldn't find the answer so far.
I'm using the following code to export my GridView into Excel file:
protected void btnExportClick(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
string strFileName = "Report_" + DateTime.Now.ToShortDateString() + ".csv";
builder.Append("Firld1,Filed2,Field3,Field4,Field5" + Environment.NewLine);
foreach (GridViewRow row in gvMOSS2Merchants.Rows)
{
string f1= row.Cells[0].Text;
string f2= row.Cells[1].Text;
string f3= row.Cells[2].Text;
string f4= row.Cells[3].Text;
string f5= row.Cells[4].Text;
builder.Append(f1+ "," + f2+ "," + f3+ "," + f4+ "," + f5+ Environment.NewLine);
}
Response.Clear();
Response.ContentType = "text/cvs";
Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
Response.Write(builder.ToString());
Response.End();
}
When clicking on the button, the file is being created, but it has only headers and no data inside.
What can be wrong with that logic?
The following code works for me
this was called in button onclick event
OnClick="ExportExcel"
EXCEL EXPORT CODE
protected void ExportExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=YourFileName" + DateTime.Now.ToString() + ".csv");
Response.Charset = "UTF8";
Response.ContentType = "application/text";
gridviewID.AllowPaging = false;
loadgrid();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Columns[k].HeaderText.ToString() + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < gridviewID.Rows.Count; i++)
{
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Rows[i].Cells[k].Text.Replace(",", " & ").Replace("\n", " ").Replace("\r", " ").ToString() + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
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();
}

Convert literal to Excel spreadsheet

I have a GridView and a few columns are literal:
<asp:TemplateField HeaderText="Next Service Date">
<ItemTemplate>
<asp:Literal ID="litNextSvcDate" runat="server">/asp:Literal>
</ItemTemplate>
I want to convert this GridView to an Excel spreadsheet and all the boundfield columns display on the spreadsheet but not the literals. Here is the code to convert the Grid to Excel:
protected void ToExcel(GridView grid, string Name, string FileName)
{
if (!FileName.Contains(".xls"))
{
FileName = FileName + ".xls";
}
string style = "<style><!--table#page{mso-header-data:\"&C" + Name + " Date/: &D/ Page &P\"; mso-page-orientation:landscape; mso-page-scale:89;} br {mso-data-placement:same-cell;} --></style>";
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName + "");
this.EnableViewState = false;
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write(style);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\">");
Response.Write("<!--[if gte mso 9]>");
Response.Write("<xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>" + Name + " Table</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Panes>");
Response.Write("</x:Panes>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("<x:Scale>89</x:Scale>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]-->");
Response.Write("</head>");
Response.Write("<body>");
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
List<int> HiddenCols = new List<int>();
for(int i = 0; i < grid.Columns.Count; i++)
{
if (!grid.Columns[i].Visible)
{
HiddenCols.Add(i);
}
}
for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
{
if(HiddenCols.Contains(i))
grid.HeaderRow.Cells[i].Visible = false;
}
ClearControls(grid);
grid.RenderBeginTag(oHtmlTextWriter);
grid.HeaderRow.RenderControl(oHtmlTextWriter);
foreach (GridViewRow row in grid.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (HiddenCols.Contains(i))
row.Cells[i].Visible = false;
}
row.RenderControl(oHtmlTextWriter);
}
grid.FooterRow.RenderControl(oHtmlTextWriter);
grid.RenderEndTag(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Write("</body>");
Response.Write("</html>");
Response.End();
}

How to export BLOB data from MySQL to be embeded into spreadsheets like Kingsoft or Excel

Is there any way to automatically embed blob attachment into excel?
Header1 | Header2 | Header3 | Attachment
Record11 | Record12 | Record13| Blob data 1
My current method is output stream of text to a file in csv.
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Report.csv");
Response.Charset = "";
Response.ContentType = "application/text";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < grdReport.Columns.Count; k++)
{
sb.Append(grdReport.Columns[k].HeaderText + ',');
}
sb.Append("\r\n");
foreach (GridViewRow row in grdReport.Rows)
{
Label label1 = (Label)row.FindControl("lblCompany");
Label label2 = (Label)row.FindControl("lblDocNum");
Label label3 = (Label)row.FindControl("lblDocType");
string str = label1.Text + "," + label2.Text + "," + label3.Textt;
sb.Append(str);
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}

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

Categories