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);
}
Related
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.
whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#
cheers..
The simplest way is to simply write either csv, or html (in particular, a <table><tr><td>...</td></tr>...</table>) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...
Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a DataTable, looping over the rows).
public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
{
if (data == null) throw new ArgumentNullException("data");
if (string.IsNullOrEmpty(filename)) filename = "export.csv";
HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
// remove this line if you don't want to prompt the user to save the file
resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
// if not saving, try: "application/ms-excel"
resp.ContentType = "text/csv";
string csv = GetCsv(headers, data);
byte[] buffer = resp.ContentEncoding.GetBytes(csv);
resp.AddHeader("Content-Length", buffer.Length.ToString());
resp.BinaryWrite(buffer);
resp.End();
}
static void WriteRow(string[] row, StringBuilder destination)
{
if (row == null) return;
int fields = row.Length;
for (int i = 0; i < fields; i++)
{
string field = row[i];
if (i > 0)
{
destination.Append(',');
}
if (string.IsNullOrEmpty(field)) continue; // empty field
bool quote = false;
if (field.Contains("\""))
{
// if contains quotes, then needs quoting and escaping
quote = true;
field = field.Replace("\"", "\"\"");
}
else
{
// commas, line-breaks, and leading-trailing space also require quoting
if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
|| field.StartsWith(" ") || field.EndsWith(" "))
{
quote = true;
}
}
if (quote)
{
destination.Append('\"');
destination.Append(field);
destination.Append('\"');
}
else
{
destination.Append(field);
}
}
destination.AppendLine();
}
static string GetCsv(string[] headers, IEnumerable<string[]> data)
{
StringBuilder sb = new StringBuilder();
if (data == null) throw new ArgumentNullException("data");
WriteRow(headers, sb);
foreach (string[] row in data)
{
WriteRow(row, sb);
}
return sb.ToString();
}
You can do it in this way:
private void ExportButton_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dataGrid);
dataGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
Complete example here.
SpreadsheetGear for .NET will do it.
You can see live ASP.NET samples with C# and VB source code here. Several of these samples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download the free trial here if you want to try it yourself.
Disclaimer: I own SpreadsheetGear LLC
I'm working on a application which will export my DataGridView called scannerDataGridView to a csv file.
Found some example code to do this, but can't get it working. Btw my datagrid isn't databound to a source.
When i try to use the Streamwriter to only write the column headers everything goes well, but when i try to export the whole datagrid including data i get an exeption trhown.
System.NullReferenceException: Object reference not set to an instance
of an object. at Scanmonitor.Form1.button1_Click(Object sender,
EventArgs e)
Here is my Code, error is given on the following line:
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
//csvFileWriter = StreamWriter
//scannerDataGridView = DataGridView
private void button1_Click(object sender, EventArgs e)
{
string CsvFpath = #"C:\scanner\CSV-EXPORT.csv";
try
{
System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
string columnHeaderText = "";
int countColumn = scannerDataGridView.ColumnCount - 1;
if (countColumn >= 0)
{
columnHeaderText = scannerDataGridView.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + scannerDataGridView.Columns[i].HeaderText;
}
csvFileWriter.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in scannerDataGridView.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
csvFileWriter.WriteLine(dataFromGrid);
}
}
}
csvFileWriter.Flush();
csvFileWriter.Close();
}
catch (Exception exceptionObject)
{
MessageBox.Show(exceptionObject.ToString());
}
LINQ FTW!
var sb = new StringBuilder();
var headers = dataGridView1.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var cells = row.Cells.Cast<DataGridViewCell>();
sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
And indeed, c.Value.ToString() will throw on null value, while c.Value will correctly convert to an empty string.
A little known feature of the DataGridView is the ability to programmatically select some or all of the DataGridCells, and send them to a DataObject using the method DataGridView.GetClipboardContent(). Whats the advantage of this then?
A DataObject doesn't just store an object, but rather the representation of that object in various different formats. This is how the Clipboard is able to work its magic; it has various formats stored and different controls/classes can specify which format they wish to accept. In this case, the DataGridView will store the selected cells in the DataObject as a tab-delimited text format, a CSV format, or as HTML (*).
The contents of the DataObject can be retrieved by calling the DataObject.GetData() or DataObject.GetText() methods and specifying a predefined data format enum. In this case, we want the format to be TextDataFormat.CommaSeparatedValue for CSV, then we can just write that result to a file using System.IO.File class.
(*) Actually, what it returns is not, strictly speaking, HTML. This format will also contain a data header that you were not expecting. While the header does contain the starting position of the HTML, I just discard anything above the HTML tag like myString.Substring(IndexOf("<HTML>"));.
Observe the following code:
void SaveDataGridViewToCSV(string filename)
{
// Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
// Select all the cells
dataGridView1.SelectAll();
// Copy selected cells to DataObject
DataObject dataObject = dataGridView1.GetClipboardContent();
// Get the text of the DataObject, and serialize it to a file
File.WriteAllText(filename, dataObject.GetText(TextDataFormat.CommaSeparatedValue));
}
Now, isn't that better? Why re-invent the wheel?
Hope this helps...
Please check this code.its working fine
try
{
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
//Add the Header row for CSV file.
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
csv += column.HeaderText + ',';
}
//Add new line.
csv += "\r\n";
//Adding the Rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value != null)
{
//Add the Data rows.
csv += cell.Value.ToString().TrimEnd(',').Replace(",", ";") + ',';
}
// break;
}
//Add new line.
csv += "\r\n";
}
//Exporting to CSV.
string folderPath = "C:\\CSV\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
File.WriteAllText(folderPath + "Invoice.csv", csv);
MessageBox.Show("");
}
catch
{
MessageBox.Show("");
}
Found the problem, the coding was fine but i had an empty cell that gave the problem.
Your code was almost there... But I made the following corrections and it works great. Thanks for the post.
Error:
string[] output = new string[dgvLista_Apl_Geral.RowCount + 1];
Correction:
string[] output = new string[DGV.RowCount + 1];
Error:
System.IO.File.WriteAllLines(filename, output, System.Text.Encoding.UTF8);
Correction:
System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
The line "csvFileWriter.WriteLine(dataFromGrid);" should be moved down one line below the closing bracket, else you'll get a lot of repeating results:
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
}
csvFileWriter.WriteLine(dataFromGrid);
I think this is the correct for your SaveToCSV function : ( otherwise Null ...)
for (int i = 0; i < columnCount; i++)
Not :
for (int i = 1; (i - 1) < DGV.RowCount; i++)
This is what I been using in my projects:
void export_csv(string file, DataGridView grid)
{
using (StreamWriter csv = new StreamWriter(file, false))
{
int totalcolms = grid.ColumnCount;
foreach (DataGridViewColumn colm in grid.Columns) csv.Write(colm.HeaderText + ',');
csv.Write('\n');
string data = "";
foreach (DataGridViewRow row in grid.Rows)
{
if (row.IsNewRow) continue;
data = "";
for (int i = 0; i < totalcolms; i++)
{
data += (row.Cells[i].Value ?? "").ToString() + ',';
}
if (data != string.Empty) csv.WriteLine(data);
}
}
}
How can I export a dataset to file that can be opened by Excel 2003 ?
will you elaborate it ? because it is diffculties to understand the CSV/TSV
marc will u give us a sample for doing it .v now ony heard the terms csv/tsv
I think This will help you. Use http handler
<%# WebHandler Language="C#" Class="DownloadAllEvent" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
public class DownloadAllEvent : IHttpHandler
{
const int BUFFERSIZE = 1024;
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
response.BufferOutput = true;
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=Events.csv");
response.Cache.SetCacheability(HttpCacheability.NoCache);
//string csvfile = request.QueryString["csvfile"];
string strNoofIds = request.QueryString["NoofIds"];
// declare variables or do something to pass parameter to writecalEntry function
writeCalEntry(response.Output, strguid, sectionid);
response.End();
}
public void writeCalEntry(TextWriter output, string[] strguid,string sectionid)
{
DataTable dt = createDataTable();
DataRow dr;
StringBuilder sbids = new StringBuilder();
// process table if neeed.. use following code to create CSV format string from table
string separator;
separator = ","; //default
string quote = "\"";
//create CSV file
//StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);
//write header line
StringBuilder sb = new StringBuilder();
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
//sw.Write(TheDataTable.Columns[i]);
sb.Append(dt.Columns[i]);
if (i < iColCount - 1)
{
//sw.Write(separator);
sb.Append(separator);
}
}
//sw.Write(sw.NewLine);
sb.AppendLine();
//write rows
foreach (DataRow tempdr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(tempdr[i]))
{
string data = tempdr[i].ToString();
data = data.Replace("\"", "\\\"");
//sw.Write(quote + data + quote);
sb.Append(quote + data + quote);
}
if (i < iColCount - 1)
{
//sw.Write(separator);
sb.Append(separator);
}
}
//sw.Write(sw.NewLine);
sb.AppendLine();
}
//sw.Close();
UnicodeEncoding uc = new UnicodeEncoding();
output.WriteLine(sb);
}
public static DataTable createDataTable()
{
DataTable dt = new DataTable("EventsData");
// create tables as needed which will be converted to csv format.
return dt;
}
call this httphandler file where you want to export data in to excell format as
Response.Redirect("downloadFile.ashx");
you can send parametres also in Response.Redirect which can be fetched in .ashx file.
I think this will hepl you.
Probably the easiest route is to export individual tables as csv/tsv. The 'net is full of samples of this.
If you want to do it in 2003, you're already six years too late. ;)
If you meant something else by "2003", maybe you could clarify and people could give a better answer (although the previous answer, export as CSV, is a pretty good one).
XML Spreadsheet could be what you're looking for.
Look at this answer.
The best way that I've personally found is to use XML and the spreadsheet component.
An example code would be far too messy to post here, but start here and see where it leads:
http://msdn.microsoft.com/en-us/library/aa140062.aspx
whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#
cheers..
The simplest way is to simply write either csv, or html (in particular, a <table><tr><td>...</td></tr>...</table>) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...
Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a DataTable, looping over the rows).
public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
{
if (data == null) throw new ArgumentNullException("data");
if (string.IsNullOrEmpty(filename)) filename = "export.csv";
HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
// remove this line if you don't want to prompt the user to save the file
resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
// if not saving, try: "application/ms-excel"
resp.ContentType = "text/csv";
string csv = GetCsv(headers, data);
byte[] buffer = resp.ContentEncoding.GetBytes(csv);
resp.AddHeader("Content-Length", buffer.Length.ToString());
resp.BinaryWrite(buffer);
resp.End();
}
static void WriteRow(string[] row, StringBuilder destination)
{
if (row == null) return;
int fields = row.Length;
for (int i = 0; i < fields; i++)
{
string field = row[i];
if (i > 0)
{
destination.Append(',');
}
if (string.IsNullOrEmpty(field)) continue; // empty field
bool quote = false;
if (field.Contains("\""))
{
// if contains quotes, then needs quoting and escaping
quote = true;
field = field.Replace("\"", "\"\"");
}
else
{
// commas, line-breaks, and leading-trailing space also require quoting
if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
|| field.StartsWith(" ") || field.EndsWith(" "))
{
quote = true;
}
}
if (quote)
{
destination.Append('\"');
destination.Append(field);
destination.Append('\"');
}
else
{
destination.Append(field);
}
}
destination.AppendLine();
}
static string GetCsv(string[] headers, IEnumerable<string[]> data)
{
StringBuilder sb = new StringBuilder();
if (data == null) throw new ArgumentNullException("data");
WriteRow(headers, sb);
foreach (string[] row in data)
{
WriteRow(row, sb);
}
return sb.ToString();
}
You can do it in this way:
private void ExportButton_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dataGrid);
dataGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
Complete example here.
SpreadsheetGear for .NET will do it.
You can see live ASP.NET samples with C# and VB source code here. Several of these samples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download the free trial here if you want to try it yourself.
Disclaimer: I own SpreadsheetGear LLC