NewLine on CSV export of datatable - c#

I have a datatable in a .Net web app that my customers have the option to export to CSV. A few customers have complained that the CSV is not able to re-import to our application. after further review, I noticed that on some large exports, the file has line breaks in it. is there a way i can prevent this?
here is my export method
DataTable dt = (DataTable)Session["Findings"];
string fileName = "test.csv";
string delimiter = ",";
//prepare the output stream
Response.Clear();
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename={0}", fileName));
//write the csv column headers
for (int i = 0; i < dt.Columns.Count; i++)
{
Response.Write(dt.Columns[i].ColumnName);
Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
}
//write the data
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Response.Write("\"" + row[i].ToString() + "\"");
Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
}
}
Response.End();
any help would be appreciated.
thanks

Related

Best way to download excel sheet using ASP.Net

I am using the below code to download the excel file:
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MBQ.xls"));
Response.ContentType = "application/ms-excel";
DataTable dt = BindDatatable();
string str = string.Empty;
foreach (DataColumn dtcol in dt.Columns)
{
Response.Write(str + dtcol.ColumnName);
str = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dt.Rows)
{
str = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
Response.Write(str + Convert.ToString(dr[j]));
str = "\t";
}
Response.Write("\n");
}
Response.End();
In my case, the table has more than 800k records. I am applying more filters before downloading the excel sheet. What is the best way to download a excel sheet from the datatable which has hundreds of thousands of rows?
Firstly since that isn't an excel spreadsheet but a tab-separated-values file (which can be opened in excel and does what you want), then don't lie in the header as that can only bring confusion:
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MBQ.csv"));
Response.ContentType = "text/tab-separated-values";
(Strictly ".csv" is an extension normally defined as being for comma-separated-values rather than tab, but it's more commonly set up to open in Excel, LibreOffice Calc, or whatever spreadsheet program people have installed, and they'll generally consider CSV and TSV as variants of each other).
Secondly, don't buffer. You have Response.Buffer = true; set to explicitly make sure you keep masses of data in memory before sending it, you want to do the opposite, so Response.Buffer = false; is the way to go.
You might find it better still to explicitly call Response.Flush() every couple of hundred or thousand rows:
int rowCount = 0;
foreach (DataRow dr in dt.Rows)
{
str = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
Response.Write(str + Convert.ToString(dr[j]));
str = "\t";
}
Response.Write("\n");
if (unchecked(++rowCount % 1024 == 0))
Response.Flush();
}
Experiment with higher or lower values than 1024. Higher sends larger chunks which is inefficient in needing more memory to hold it, but efficient in the actual sending of the chunk is snappier, so the optimal value will be a matter of finding the best balance between those two factors.

error message after converting datatable to excel in asp.net c#

error message after converting datatable to excel in asp.net c#
below code i am using
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
DataTable dt = ds.Tables[0];
string str = string.Empty;
foreach (DataColumn dtcol in dt.Columns)
{
Response.Write(str + dtcol.ColumnName);
str = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dt.Rows)
{
str = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
Response.Write(str + Convert.ToString(dr[j]));
str = "\t";
}
Response.Write("\n");
}
Response.End();
error message is
![Your trying to open different format or corrupted file ][2]
its opening after clicking ok but i dnt want showing this message ....
where i made error...
thank you...
Your content type is wrong. You are creating a CSV output, not Excel. Change content type to text/csv and file extension to .csv.
How to use the CSV MIME-type?
Link to OpenXML SDK which let's you create any Office format: http://msdn.microsoft.com/en-us/library/office/bb448854%28v=office.15%29.aspx

How to export from DataTable to Excel file in text format (even if there are numbers)

I am using the following procedure to create an Excel spreadsheet from a DataTable:
protected void UploadDataTableToExcel(DataTable dtEmp, string filename)
{
string attachment = "attachment; filename=" + filename;
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn dtcol in dtEmp.Columns)
{
Response.Write(tab + dtcol.ColumnName);
tab = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dtEmp.Rows)
{
tab = "";
for (int j = 0; j < dtEmp.Columns.Count; j++)
{
Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
It works fine except when the cell only has numbers. For example:
This "6969062201223401504" becomes "6.96902E+18"
This "076854957" becomes "76854957"
I would like the Excel spreadsheet to preserve every column as text, instead of converting them into integers

Export datatable value to word using c#

I am new to asp.net and need to create a project. My requirement is I have a table where I will store data. This is my main table. Under each id I have a separate table:
Msg_id Src Dest
701 RADAR MSC
702 MSC RADAR
Msg_id Message_size Mgs_desc
701 256 PFM_Load
Like that it continues... I have 3 dropdown lists. The 1st one is msg_id, the 2nd is src and the 3rd is dest. I also have a submit button the user can select any one of the dropdown lists and the corresponding table should be displayed in MS-Word.
You will need to create report of this data in .NET
Use EnableRenderExtension( "HTML4.0", "MS Word" ); for this purpose.
Then will have to export that report into word file.
Follow link:
http://www.codeproject.com/Articles/35225/Advanced-Report-Viewer
Or
Step by Step Approach:
http://www.accelebrate.com/sql_training/ssrs_2008_tutorial.htm
Hope Its helpful.
u can use this:
THis code for export into csv formate which can open in both msword&msexcel:
private void OutPutFileToCsv(DataTable dt, string fileName, string seperator)
{
StringWriter stringWriter = new StringWriter();
Int32 iColCount = dt.Columns.Count;
for (Int16 i = 0; i < iColCount; i++)
{
stringWriter.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
stringWriter.Write(dr[i].ToString().Trim());
}
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
}
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName));
Response.ContentEncoding = Encoding.GetEncoding("iso-8859-1");
//Response.BinaryWrite(Encoding.Unicode.GetPreamble());
Response.Write(stringWriter.ToString());
Response.End();
}
just pass your datatable in function and get grid data in ms-word.
private void ExportToWord(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "DownloadReport.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/msword";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Hope it helps you.

Display columns and rows after exporting data from gridview to excel

Hi all i am having a task to export gridview data to excel which i have done using the forums and articles available.
But i would like to display complete excel columns after the data was imported to excel, means expect the place occupied by the grid content i would like to display the remaining columns of the excel as it is.
Sample the normal way of exporting the we do in common is as follows
My requirement is to show as follows
I followed as per here
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
See your code to export you have removed the border of the excel generated in the code.
You can use the following code to do it
protected void btnExportCSV_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
-->Return only hearder,not view data.Help Me !
Thank you !
Email:tsmcstcd#gmail.com

Categories