使用OpenXML和C#,Integers和DateTime导出到Excel

我正在写一个应用程序,应该从地图应用程序导出数据。 此应用程序正在使用Silverlight,并方便导出到Excel我正在使用此库。 所有的数据默认都以string表示。 当我写电子表格时,我尝试parsing每个string,看看它是哪种types:

string str = kvp.Value; int i = 0; long l = 0; decimal dec = 0; DateTime dt; if (int.TryParse(str, out i)) doc.Workbook.Sheets[0].Sheet.Rows[r].Cells[c].SetValue(i); else if (decimal.TryParse(str, out dec)) doc.Workbook.Sheets[0].Sheet.Rows[r].Cells[c].SetValue(dec); else if (long.TryParse(str, out l)) doc.Workbook.Sheets[0].Sheet.Rows[r].Cells[c].SetValue(l); else if (DateTime.TryParse(str, out dt)) doc.Workbook.Sheets[0].Sheet.Rows[r].Cells[c].SetValue(dt); else doc.Workbook.Sheets[0].Sheet.Rows[r].Cells[c].SetValue(str); 

这很好,除了DateTime,当我试图parsing一个社会安全号码,在我的情况是12个字符长。

社会安全号码被parsing为十进制数字,并以科学forms显示在Excel中。 从我通过阅读中得到的信息来看,它似乎是Excel中的一个限制。 如果我标记单元格,但是我在顶部栏中看到了可以写公式的正确数字。 到目前为止,我已经解决了这个问题,简单地把这个数字作为一个string,让最终用户现在处理它,但我真的很希望它是一个在完成文档中的数字。 这可能吗?

但是,我的想法真是令人难以置信的是DateTime。 date格式如下所示:10/15/2013 1:10:00 AM。 它在Excel文件中看起来像这样:2455075。

我检查了date格式的源代码,但我似乎不够熟练,看看是否有任何错误。 对于任何人,你可以在这里查看 。

SetValue函数应该自动识别以下types:

  • 布尔
  • 约会时间
  • 十进制
  • 例外
  • SharedStringDefinition

我很抱歉,这个post很长。 它归结为这些问题:

  • 我可以让Excel处理长数字没有科学记数法编程方式?
  • 为什么DateTime输出这样一个奇怪的格式?

要以date格式设置单元值,您必须将DateTime转换为OLE自动date。 你也可以创build更清晰的方法来编写单元格值。 像这样的东西:

 public bool UpdateValue(WorkbookPart wbPart, string sheetName, string addressName, string value, UInt32Value styleIndex, CellValues dataType) { // Assume failure. bool updated = false; Sheet sheet = wbPart.Workbook.Descendants<Sheet>().Where( (s) => s.Name == sheetName).FirstOrDefault(); if (sheet != null) { Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(sheet.Id))).Worksheet; Cell cell = InsertCellInWorksheet(ws, addressName); if (dataType == CellValues.SharedString) { // Either retrieve the index of an existing string, // or insert the string into the shared string table // and get the index of the new item. int stringIndex = InsertSharedStringItem(wbPart, value); cell.CellValue = new CellValue(stringIndex.ToString()); } else { cell.CellValue = new CellValue(value); } cell.DataType = new EnumValue<CellValues>(dataType); if (styleIndex > 0) cell.StyleIndex = styleIndex; // Save the worksheet. ws.Save(); updated = true; } return updated; } 

然后像这样调用这个方法(第一个调用是为String而第二个为DateTime):

 UpdateValue(workbookPart, wsName, "D14", "Some text", 0, CellValues.String); UpdateValue(workbookPart, wsName, "H13", DateTime.Parse("2013-11-01").ToOADate().ToString(CultureInfo.InvariantCulture), 0, CellValues.Date);