How I can export a datatable to MS word 2007, excel 2007,csv from asp.net? - asp.net

I am using the below code to Export DataTable to MS Word,Excel,CSV format & it's working fine. But problem is that this code export to MS Word 2003,Excel 2003 version. I need to Export my DataTable to Word 2007,Excel 2007,CSV because I am supposed to handle more than 100,000 records at a time and as we know Excel 2003 supports for only 65,000 records.
Please help me out if you know that how to export DataTable or DataSet to MS Word 2007,Excel 2007.
public static void Convertword(DataTable dt, HttpResponse Response,string filename)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
public static void Convertexcel(DataTable dt, HttpResponse Response, string filename)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
public static void ConvertCSV(DataTable dataTable, HttpResponse Response, string filename)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".csv");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "Application/x-msexcel";
StringBuilder sb = new StringBuilder();
if (dataTable.Columns.Count != 0)
{
foreach (DataColumn column in dataTable.Columns)
{
sb.Append(column.ColumnName + ',');
}
sb.Append("\r\n");
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
if(row[column].ToString().Contains(',')==true)
{
row[column] = row[column].ToString().Replace(",", "");
}
sb.Append(row[column].ToString() + ',');
}
sb.Append("\r\n");
}
}
Response.Write(sb.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}

Use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Related

What is the best way to create .xls from datatable in asp .Net c#?

i have a datatable and i want to export excel from that,
my datatable contains unicode characters (persian characters) and i want to convert it to .xls files correctly.
i was wonder is it possible to do that with Stimulsoft?
This is a common method I use
public void ExportDetails(DataTable tempDataTable, string FileName)
{
try
{
System.IO.StringWriter objStringWriter1 = new System.IO.StringWriter();
System.Web.UI.WebControls.GridView gridView1 = new System.Web.UI.WebControls.GridView();
System.Web.UI.HtmlTextWriter objHtmlTextWriter1 = new System.Web.UI.HtmlTextWriter(objStringWriter1);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
gridView1.DataSource = tempDataTable;
gridView1.DataBind();
gridView1.HeaderStyle.Font.Bold = true;
gridView1.HeaderStyle.BackColor = System.Drawing.Color.Gray;
gridView1.RenderControl(objHtmlTextWriter1);
gridView1.Dispose();
HttpContext.Current.Response.Write(objStringWriter1.ToString());
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
}
}

wrong output when transfering datagrid to word/excel/pdf

hye, i have made this code which i have tried separately from my current web and it work perfectly but when i combine it with my web, i didn't get the output that was generated in the gridview. here is the code that i had used.
protected void Wordbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
wordmax();
}
if (curdata.Checked == true)
{
wordcur();
}
}
protected void excelbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
excelmax();
}
if (curdata.Checked == true)
{
excelcur();
}
}
protected void pdfbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
pdfmax();
}
if (curdata.Checked == true)
{
pdfcur();
}
}
public void wordmax()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=MaxdataExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
gridmaxdata.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void wordcur()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=CurrentDataExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
gridcurdata.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void excelmax()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=MaxDataExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
//Change the Header Row back to white color
gridmaxdata.HeaderRow.Style.Add("background-color", "#FFFFFF");
gridmaxdata.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void excelcur()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=CurrentdataExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
//Change the Header Row back to white color
gridcurdata.HeaderRow.Style.Add("background-color", "#FFFFFF");
gridcurdata.RenderControl(hw);
//---------------------------------------------------------------------------------
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void pdfmax()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=MaxDataExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
gridmaxdata.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
public void pdfcur()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=CurrentdataExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
gridcurdata.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
this is the code that i used to create the datagridview
public void maxdatatable()
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\webradiation\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True";
//Bind SQLDataSource to GridView for max data
// Create SQLDataSource.
SqlDataSource sqlDataSource1 = new SqlDataSource();
sqlDataSource1.ID = "SqlDataSource123";
this.Page.Controls.Add(sqlDataSource1);
// Bind ConnectionString to SQLDataSource.
sqlDataSource1.ConnectionString = connectionString;
// Retrieve records
sqlDataSource1.SelectCommand = "SELECT top 30 [date], [data] FROM [loc1] WHERE (([data] >= '2') AND (([date] >= '" + combdatetime11.ToString() + "') AND ([date] <= '" + combdatetime21.ToString() + "'))) ORDER BY [data] DESC, [date] DESC";
gridmaxdata.DataSource = sqlDataSource1;
gridmaxdata.DataBind();
}
public void currdata()
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\webradiation\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True";
// Create SQLDataSource.
SqlDataSource sqlDataSource2 = new SqlDataSource();
sqlDataSource2.ID = "SqlDataSource12";
this.Page.Controls.Add(sqlDataSource2);
// Bind ConnectionString to SQLDataSource.
sqlDataSource2.ConnectionString = connectionString;
// Retrieve records
sqlDataSource2.SelectCommand = "SELECT [date], [data] FROM [loc1] WHERE (([date] >= '" + combdatetime11.ToString() + "') AND ([date] < '" + combdatetime21.ToString() + "'))";
gridcurdata.DataSource = sqlDataSource2;
gridcurdata.DataBind();
}
for the word document, the output that i got is
(div) (/div)
*i have to used "(" and ")" to replace "<" and ">" because this pageweb make it disappear
the excel is like this
(style) .textmode { mso-number-format:\#; } (/style)(div)(div)
the pdf file i got an error saying that the document does not have pages.
do you not where did i do wrong?
you can create a extension function to convert the datasource datatable to excel and then send it to client using Response.WriteFile method
using OfficeOpenXml;
public static class Extensions
{
public static void ToExcel(this DataTable source, string destinationXlsxPath)
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
ws.Cells["A1"].LoadFromDataTable(source, true);
FileInfo file = new FileInfo(destinationXlsxPath);
pck.SaveAs(file);
}
}
}
EPPlus: http://epplus.codeplex.com/

Export Data table With Arabic Data to Excel

I am Having a Data Table which consists of arabic data.
When I am Exporting it to excel I am unable to get the Arabic data correctly.
Currently my code is as below,
public void ExportExcel(DataTable table, string filename)
{
if (table != null && filename != "")
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;attachment;filename=" + filename + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView GrdExcel = new GridView();
GrdExcel.AllowPaging = false;
GrdExcel.DataSource = table;
GrdExcel.DataBind();
for (int i = 0; i < GrdExcel.Rows.Count; i++)
{
GridViewRow row = GrdExcel.Rows[i];
row.Attributes.Add("class", "text");
}
GrdExcel.RenderControl(htmlWrite);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Output.Write(stringWrite.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
EDIT 1:
Below is the final code which has worked for me
////If you want the option to open the Excel file without saving than
////comment out the line below
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;attachment;filename=" + filename + ".xls");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
DataGrid grdExcel = new DataGrid();
grdExcel.AllowPaging = false;
grdExcel.DataSource = table;
grdExcel.DataBind();
foreach (DataGridItem i in grdExcel.Items)
{
foreach (TableCell tc in i.Cells)
tc.Attributes.Add("class", "text");
}
grdExcel.RenderControl(htmlWrite);
string style = #"<style> .text { mso-number-format:\#; } </style> ";
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
This was written by referring few articles from the web .Hope it helps
add this code to your code:
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
Every string wrap in Encoding.UTF8.GetString (for ex: Encoding.UTF8.GetString(str))
and in web.config:
<system.web>
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="he-IL"/>
</system.web>
he-IL is in my case, write your language culture respectively

Passing a grid to a function used to export to excel

I have a method that is used to export the data to excel.Till now I have been passing table to the method.But now I wish to pass the grid data so that I do not have to call the procedures for different instances for getting different filtered data sets.
is there a way to do so?
public void ExportToExcel(DataSet ds)
{
if (ds.Tables[0].Rows.Count > 0)
{
string filename = ds.Tables[1].Rows[0]["filename"].ToString() + ".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 = ds.Tables[0];
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.Clear();
Response.ClearHeaders();
Response.Charset = "";
Response.AddHeader("content-disposition", String.Concat("attachment;filename=", filename));
Response.AddHeader("Cache-Control", "max-age=0");
Response.ContentType = "application/vnd.xls";
// this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
This is the method that I am using to export to excel.

How to export an mschart chart to excel?

I have created a chart with Mschart.I want to export the created chart to excel.
I'm using following code but when I open it in excel I just see some unknown code instead of chart.
using (var chartimage = new MemoryStream())
{
ChartAmalkerd.SaveImage(chartimage, ChartImageFormat.Png);
ExportToExcel(chartimage.GetBuffer());
}
private void ExportToExcel(byte[] input)
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding(1256);
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
Response.Buffer = true;
this.EnableViewState = false;
Response.BinaryWrite(input);
Response.Flush();
Response.Close();
Response.End();
}
I have found the same issue and after making several attempts, I was able to find out the correct way. This worked for me and the code is as follows.
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = #"<Table><tr><td><img src='" + imgPath2 + #"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
Hope this helps.
I also came across such scenario in one of my project.
Here is the solution.
http://haseet.blogspot.in/2013/02/develop-chart-in-aspnet-with-export-to-excel-pdf-msoffice-openoffice.html
Add this code for your globalization, this works for me.
Dim info As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
Thread.CurrentThread.CurrentCulture = info
Thread.CurrentThread.CurrentUICulture = info
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.HeaderEncoding = System.Text.Encoding.UTF8

Resources