Technology: C# ASP.NET
Level: Expert
Depth: Medium
I, once, had to present a save-as dialogue that would export the content of a GridView into csv and the database would contain Japanese texts. Export was all fine and the file was read fine from Visual Studio itself. However, when the csv was opened from Excel, the Japanese texts came all garbage.
This could have been for my PC doesn’t have Japanese locales and fonts. But the PC with such features also read it same. Here I present a way that solved this problem.
protected void ImageButton_CSV_Click(object sender, ImageClickEventArgs e)
{
…
MyDataSet.MyDataTable exportTable = …
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentEncoding = Encoding.GetEncoding(“shift_JIS”);
for (int i = 1; i < exportTable.Columns.Count; i++)
{
context.Response.Write(exportTable.Columns[i].ColumnName + “,”);
}
context.Response.Write(Environment.NewLine);
string orig_string = “”;
byte[] unicodeBytes = null;
byte[] codBytes = null;
char[] codChars = null;
string codString = “”;
Encoding cod = Encoding.GetEncoding(“shift_JIS”);
Encoding unicode = Encoding.UTF8;
for (int i = 1; i < exportTable.Rows.Count; i++)
{
for (int j = 0; j < exportTable.Columns.Count; j++)
{
orig_string = exportTable[i][j].ToString().Replace(“,”, string.Empty).Replace(“ ”, string.Empty) + “,”;
unicodeBytes = unicode.GetBytes(orig_string);
codBytes = Encoding.Convert(unicode, cod, unicodeBytes);
codChars = new char[cod.GetCharCount(codBytes, 0, codBytes.Length)];
cod.GetChars(codBytes, 0, codBytes.Length, codChars, 0);
codString = new string(codChars);
context.Response.Write(codString);
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = “text/csv”;
context.Response.AppendHeader(“Content-Disposition”, “attachment; filename=my_file.csv”);
context.Response.End();
}
The codes in the bold do the actual trick. The content encoding and writing to the response in the correct manner is all that needs to be done.
This, however, is not limited to csv exports. You can try with other file formats too.
Cheers and Cheese (Y)
Recent Comments