I'm exporting some data from a GridView to a .txt file.
This is the code:
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
string FileName = "Export" + DateTime.Now + ".txt";
StringBuilder strbldr = new StringBuilder();
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Cache.SetCacheability(HttpCacheability.NoCache);
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//separting header columns text with comma operator
strbldr.Append(GridView1.Columns[i].HeaderText + ',');
}
//appending new line for gridview header row
strbldr.Append("\n");
for (int j = 0; j < GridView1.Rows.Count; j++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//separating gridview columns with comma
strbldr.Append(GridView1.Rows[j].Cells[k].Text + ',');
strbldr.Replace("<", "<");
strbldr.Replace(">", ">");
}
//appending new line for gridview rows
strbldr.Append("\n");
}
GridView1.AllowPaging = false;
Response.Output.Write(strbldr.ToString());
Response.End();
}
protected void Button3_Click(object sender, EventArgs e)
{
ExportGridToExcel();
}
This works, however I need to remove all html tags in the export as the above code seems to add <p> tags to the different columns? Anybody know how I can do this?
You could use utility function based on regex to remove html tags:
public string RemoveHtmlTags(string source)
{
return Regex.Replace(source, "<.*?>", "");
}
This will replace all tags like "<b>" or "<span/>" with empty string.
Related
When I am trying to download Project Name, I'm getting a different character for special charter in the Excel export.
What should I do so all my special characters are correctly shown?
protected void lnkExportToExcel_Click(object sender, EventArgs e)
{
//INS1-219
DataTable dt1 = DataHelper.ExecuteQuery(Session["strForExcelReport"].ToString());
DataTable dt3 = new DataTable();
dt3.Columns.Add("Project Code");
dt3.Columns.Add("Project Name");
/// many more columns
foreach (DataRow dr in dt1.Rows)
{
drnew["Project Code"] = dr["ProjectCode"].ToString();
drnew["Project Name"] = dr["ProjectName"].ToString();
drnew["Client"] = dr["OrganizationName"].ToString();
// many, many business rules
dt3.Rows.Add(drnew);
}
// DataTable is now complete
string attachment = "attachment; filename=ProjectInHandDetailsList_" + DateTime.Now.ToString("dd MMM yyyy") + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt3.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt3.Rows)
{
tab = "";
for (i = 0; i < dt3.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
//END INS1-219
}
With above code a projectname comes out in the Excel sheet like this:
Royal Free Flash Case Study 3–Pleuritic Chest Pa
while this is the value from the database:
Royal Free Flash Case Study 3 – Pleuritic Chest Pa
How do I prevent those strange characters from showing up?
You need to use an Encoding, both in the ContentEncoding header and a StreamWriter to write the strings to the OutputStream. Encoding mismatches are the reason for the strange replacement of characters.
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
// set the contentencoding of the http content
Response.ContentEncoding = Encoding.UTF8;
// use a streamwriter that knows how to write strings in
// a specified encoding to a stream
using(var sw = new StreamWriter(Response.OutputStream, Response.ContentEncoding))
{
string tab = "";
foreach (DataColumn dc in dt3.Columns)
{
// use the StreamWriter
sw.Write(tab + dc.ColumnName);
tab = "\t";
}
sw.Write("\n");
int i;
foreach (DataRow dr in dt3.Rows)
{
tab = "";
for (i = 0; i < dt3.Columns.Count; i++)
{
sw.Write(tab + dr[i].ToString());
tab = "\t";
}
sw.Write("\n");
}
}
Response.End();
While exporting Datatable to Excel some columns to fall into a new line. I don't know what the problem is. My code is below:
string attachment = "attachment; filename=Test.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in transposedTable.Columns)
{
Response.Write(tab + dc.ColumnName);
//tab = "\t";
}
Response.Write("\t");
int i;
foreach (DataRow dr in transposedTable.Rows)
{
Response.Write("\n");
tab = "";
for (i = 0; i < transposedTable.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\t");
}
Response.End();
I have tried many ways, but didn't get the exact issue. Is the issue with excel in machine or with my code?
It seems possible that your DataRow data contains newline characters, that is one reason why newlines might be appearing in your data.
Swapping:
Response.Write(tab + dr[i].ToString());
For:
string replacement = Regex.Replace(dr[i].ToString(), #"\t|\n|\r", "");
Response.Write(tab + replacement);
May fix the problem if I did diagnose it correctly.
I am exporting a csv file with the following code from a datatable. however names with accents are not exported correctly
http://screencast.com/t/i9N2mB34DL
var dt=JobContext.GetEngagementLetterReport(SPContext.Current.Site, int.Parse(rdlOption.SelectedValue));
var columnNames = new List<string>
{
Constants.SearchFields.Client.ClientCode,
Constants.SearchFields.Client.ClientName,
Constants.SearchFields.Job.JobCode,
Constants.SearchFields.Job.JobName,
Constants.SearchFields.Job.JobPartner,
Constants.SearchFields.Job.JobDirector,
Constants.SearchFields.Job.JobManager,
Constants.SearchFields.Job.BillContact,
Constants.SearchFields.Job.LineOfService,
Constants.SearchFields.Job.BusinessUnit,
Constants.SearchFields.Job.OperatingUnit,
"JobSiteUrl",
"FileNameUrl"
};
ExcelHelper.ExportDatatabletoExcel(dt, columnNames);
public static void ExportDatatabletoExcel(DataTable dt, List<string> columnNames)
{
try
{
const string attachment = "attachment; filename=elreport.csv";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
if (!columnNames.Contains(dc.ColumnName)) continue;
HttpContext.Current.Response.Write(tab + dc.ColumnName);
tab = ";";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
if(!columnNames.Contains(dt.Columns[i].ColumnName)) continue;
HttpContext.Current.Response.Write(tab + dr[i].ToString());
tab = ";";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
string errorMessage = String.Format("ExportToExcelError: {0}", ex.Message);
LoggingService.LogError(LoggingCategory.General, ex, errorMessage);
throw;
}
}
Try adding the following after setting the content type.
// This is the missing part from your original code to set the charset and encoding - if this does not work, replace it with appropriate value, eg
Response.Charset = "utf-8";
Response.ContentEncoding = Encoding.UTF8;
// You might want to use this content type or experiment with appropriate MIME type
Response.ContentType = "text/csv";
TQ.
I am using a method that accepts datatable and transform it into CSV. The problem is, (1) when I try to call this method, succeeding process/commands will never be executed. Also (2) list box contents from the calling form were cleared out after calling this method. Can anyone help me out on this? I have included the method below for reference.
public void DataTableToCSV(string fileName, DataTable dt)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace(" ", "").Replace("/", "")));
Response.Charset = "";
Response.ContentType = "application/vnd.csv";
System.IO.StringWriter sWriter;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sWriter = new System.IO.StringWriter(sb);
string Str;
for (int k = 0; k <= (dt.Columns.Count - 1); k++)
{
sWriter.Write(dt.Columns[k].ColumnName + ",");
}
sWriter.WriteLine(",");
for (int i = 0; i <= (dt.Rows.Count - 1); i++)
{
for (int j = 0; j <= (dt.Columns.Count - 1); j++)
{
Str = (dt.Rows[i][j].ToString().Replace(",", ""));
if (Str == " ")
Str = "";
Str = (Str + ",");
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
Response.Write(sb.ToString());
Response.End();
}
Regarding (1) - Response.End() throws ThreadAbortException internally, which basically terminates the normal page life-cycle and 'jumps ahead' to the EndRequest event. So anything immediately following a call to DataTableToCSV() will not be called.
Hope this helps..
Create a second page that returns the CSV. Put a Meta refresh tag in the head of your page which redirects to this page. Because the reponse is a file, you'll never actually be redirected, but the file save dialogue will appear.
I can export my radgrid to an excel file but I want to add some more info into the sheet.
If it is possible, I would appreciate for a tutorial/sample code for doing a custom excel file generation.
<tel:radgrid runat="server" id="mygrid" skinid="RadGrid_Search_Standard">
<ExportSettings HideStructureColumns="true" />
</tel:radgrid>
Grid is databound with some datatable and I need to add some data
to add some strings above
mygrid.MasterTableView.ExportToWord()
Here's some code that I use with a Telerik Grid, rather than using the ExportToExcel function they've provided I created my own button that fires it's own export event.
I have a function (not included) called getDataSource that I use to populate the grid, you could override this or create your own to fetch the data into a DataTable and add any rows/columns/data as you see fit.
//export button calls this
private void ExportReport()
{
SetPublicVariables();
System.Data.DataTable dt = GetDataSource(false);
string exportData = buildCSVExportString(dt);
string filename = string.Format("{0} - {1}.csv",
(Master as MasterPages.Drilldown).Titlelbl.Text, CampaignTitle);
if (filename.Length > 255) filename = filename.Substring(0, 255);
ExportCSV(exportData, filename);
}
//build a string CSV
public static string buildCSVExportString(DataTable exportDT)
{
StringBuilder exportData = new StringBuilder();
// get headers.
int iColCount = exportDT.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
exportData.Append(exportDT.Columns[i].ToString());
if (i < iColCount - 1)
{
exportData.Append(",");
}
}
exportData.Append(System.Environment.NewLine);
// get rows.
foreach (DataRow dr in exportDT.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
//If the variable is a string it potentially has charaters that can't be parsed properly.
//this fixes the comma issue(which adds aditional columns). Replace and escape " with "".
if (dr[i] is string)
exportData.Append(String.Format(#"""{0}""", ((string)dr[i]).Replace("\"", #"""""")));
else
exportData.Append(dr[i].ToString());
}
if (i < iColCount - 1)
{
exportData.Append(",");
}
}
exportData.Append(System.Environment.NewLine);
}
return exportData.ToString();
}
public void ExportCSV(string content, string filename)
{
filename = RemoveIllegalPathChars(filename);
HttpResponse Response = HttpContext.Current.Response;
string ext = System.IO.Path.GetExtension(filename);
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", filename));
Response.ContentType = "text/csv; charset-UTF-8;";
Response.Clear();
Response.Write(content);
Response.End();
}
A possible way would be to modify the HTML code just before exporting. Here is how.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
RadGridName.GridExporting += (s, a) =>
{
string myHtmlCode = "<span>My HTML code goes here</span>";
a.ExportOutput = a.ExportOutput.Replace("<body>", "<body>" + myHtmlCode);
};
}
This should work for both Excel (not ExcelML) and Word.
Good luck
The only thing you need to do is add your additional page info to the ExportOutput of your arg
void yourRadGridID_GridExporting(object sender, GridExportingArgs e)
{
string additionalPageInfo= "your html code for the additional page info goes here";
e.ExportOutput = e.ExportOutput.Replace("`<body>`", "`<body>`" + additionalPageInfo);
}