简体   繁体   中英

how to export data into excel

How to export data from datatable into excel file with a proper output. i means 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)

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();

在此处输入图片说明

Row 1 appears to be the header already... your arrow points to the column labels. Are you wanting 'A' to be "Site_Site_id"? That's not how excel works.

For precision, right click and choose format. Now change the decimal precision to what every you want displayed.

在此处输入图片说明


You can also highlight all your cells and used the toolbar buttons:

在此处输入图片说明


You can try to do it in code this way:

// 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.Cells[i + 2, j + 1].NumberFormat = "0.00000000000000000"
  }
}

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

 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM