Click here to Skip to main content
15,894,294 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
How to export data from datatable into excel file with a proper output. means that first row of excel record should be the header and the display data should show all the value instead of rounding up the values. please help :)ldt_Temp (datatable),as_OutputDir (exported dir)
C#
object misValue = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = false;

            Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;

            // Headers.  
            for (int i = 0; i < ldt_Temp.Columns.Count; i++)
            {
                ws.Cells[1, i + 1] = ldt_Temp.Columns[i].ColumnName;
            }
            // Content.  
            for (int i = 0; i < ldt_Temp.Rows.Count; i++)
            {
                for (int j = 0; j < ldt_Temp.Columns.Count; j++)
                {
                    ws.Cells[i + 2, j + 1] = ldt_Temp.Rows[i][j].ToString();
                }
            }
            ws.Name = ldt_Temp.TableName;

          
            wb.SaveAs(as_OutputDir, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            wb.Close(true, misValue, misValue);
            app.Quit();
Posted
Updated 3-Oct-13 16:56pm
v3
Comments
PIEBALDconsult 3-Oct-13 23:53pm    
I use OleDb and the ACE engine to write to Excel and I haven't noticed any rounding. Do you have any examples?
Kipperr 7-Mar-17 6:17am    
Here is how I exported my DataTable into an Excel in C#.
I short, the following is the key part:

sheet.InsertDataTable(dataTable,
new InsertDataTableOptions() { ColumnHeaders = true });

That API comes from this Excel library for .NET.

Here i have one more solution to export data table to excel. You need to just create a string as per your requirement. The most important benefits of this method is file accessibility. that means if you have a Open Office instead of MS-Office this will work fine.

C#
string FileName = "Test.xls";
string fullpath = path + @"\" + FolderName + FileName;

int tblborder = 2;
StreamWriter SW;
SW = File.CreateText(fullpath);
StringBuilder objSB = new StringBuilder();
objSB.Append("<Table border=" + tblborder + "  width=100%>");

objSB.Append("<tr>");

for (int i = 0; i < ldt_Temp.Columns.Count; i++)
{
    objSB.Append("<th valign=middle>" + ldt_Temp.Columns[i].ColumnName + "</th>");
}

objSB.Append("</tr>");
objSB.Append("<tr>");

for (int i = 0; i < ldt_Temp.Rows.Count; i++)
{
      for (int j = 0; j < ldt_Temp.Columns.Count; j++)
      {
            objSB.Append("<tr>");
                objSB.Append("<td align=center>" + ldt_Temp.Rows[i][j].ToString() + "</td>");
        objSB.Append("</tr>");
      }
}

objSB.Append("</Table>");
SW.Write(objSB.ToString());
SW.Close();
Response.Redirect(filePath);
 
Share this answer
 
v2
the only way that the value will not be rounded up is to convert all the numeric values into the string values so that they can't be altered otherwise they will be rounded up automatically.
 
Share this answer
 
Comments
Member 2321293 3-Oct-13 23:23pm    
is you mean this part "ws.Cells[i + 2, j + 1] = ldt_Temp.Rows[i][j].ToString();" or change the datatable columns into system.string format first? but i did so.. work the same
kesav aggarwal 4-Oct-13 11:39am    
best way is to convert the data to string when retrieving from database so that the normal operations on database can be performed. Excel will accept the string value easily and values in the cell will be in numeric format.
 
Share this answer
 
v3
and i also find out a way to rearrange each number format for each cells, loop each cells and get the length of digit and create the format dynamically way (inside second loop)

C#
string ls_Test = cells value
     string part = ls_Test.Substring(0, ls_Test.IndexOf('.'));
     string ls_FormatDeicmal = ls_Test.Substring(part.Length + 1, ls_Test.Length - (part.Length + 1));
     string ls_DigiFormat = "";
     for (int f = 0; f < ls_FormatDeicmal.Length; f++)
     {
         ls_DigiFormat += "0";
     }
     ls_DigiFormat = "0." + ls_DigiFormat; // 0.000000000, 0.00, 0.00000
     ws.Cells[i + 2, j + 1].NumberFormat = ls_DigiFormat;
 
Share this answer
 
public void ExportToExcel()
       {
           try
           {
               this.OrderGridView.AllowPaging = false;
               this.OrderGridView.AllowSorting = false;
               this.OrderGridView.EditIndex = -1;

               // Let's bind data to GridView
               this.RefreshGrid();

// IF YOU DO NOT NEED SOME COLUMNS LIKE THE FIRST TWO IN MY EXAMPLE ADD THE FOLLOWING TWO ROWS

               OrderGridView.Columns.RemoveAt(1);
               OrderGridView.Columns.RemoveAt(0);

               OrderGridView.DataBind();
               // Let's output HTML of GridView
               Response.Clear();
               Response.ContentType = "application/vnd.xls";
               Response.AddHeader("content-disposition",
                       "attachment;filename=MyOrder.xls");
               Response.Charset = "";
               StringWriter swriter = new StringWriter();
               HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
               OrderGridView.RenderControl(hwriter);
               Response.Write(swriter.ToString());
               Response.Flush();
               Response.End();
               //HttpContext.Current.ApplicationInstance.CompleteRequest();
           }
           catch (Exception exe)
           {
               throw exe;
           }
       }


And then call the function on button click:
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
       {
           ExportToExcel();
           this.OrderGridView.AllowPaging = true;
           this.OrderGridView.AllowSorting = true;
           this.OrderGridView.EditIndex = -1;
           this.RefreshGrid();
       }


I hope it helps you!
 
Share this answer
 
v2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900