如何将数据导出到excel

时间:2013-10-04 02:30:38

标签: c# excel csv xls

如何使用适当的输出将数据从datatable导出到excel文件中。我的意思是第一行excel记录应该是标题,显示数据应显示所有值而不是舍入值。请帮助** ldt_Temp(datatable),as_OutputDir(export 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();

enter image description here

2 个答案:

答案 0 :(得分:0)

第1行似乎已经是标题...您的箭头指向列标签。你想要'A'成为“Site_Site_id”吗?这不是excel的工作方式。

要获得精确度,请右键单击并选择格式。现在将小数精度更改为您想要显示的内容。

enter image description here


您还可以突出显示所有单元格并使用工具栏按钮:

enter image description here


您可以尝试以这种方式在代码中执行此操作:

// 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"
  }
}

答案 1 :(得分:0)

我还找到了一种方法来重新排列每个单元格的每个数字格式,循环每个单元格并获得数字长度并动态创建格式

 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;