如何将DateTime,TimeSpan,string和双精度值从WPF MVVM应用程序导出到Excel?

在我的WPF MVVM Prism应用程序中,我每秒从外部设备读取一些数据(通过COM端口)(我使用System.Windows.Threading.DispatcherTimer)。 每次我读取数据填充以下缓冲区:

/// <summary> /// Represents the point on the chart. /// </summary> public class ChartPoint { #region Fields // The value from outer device. private double _value; // The date and time when the value was being obtained. private DateTime _category; #endregion #region Constructors public ChartPoint() { } public ChartPoint(DateTime category, double value) { this.Category = category; this.Value = value; } #endregion #region Properties public double Value { get { return this._value; } set { if (double.IsNaN(value) || double.IsInfinity(value)) value = 0; this._value = value; } } public DateTime Category { get { return this._category; } set { this._category = value; } } #endregion } 

我需要导出到Microsoft Excel以下数据:

 DateTime currentDate = ChartPoint.Category.Date; TimeSpan currentTime = ChartPoint.Category.TimeOfDay; double currentValue = ChartPoint.Value; 

时间值必须在用户frendly视图中,例如:09:21:54(hh:mm:ss)。 这里必须加上测量超声波束的名称。 例如:

 string measuringBeam = "beam 1"; or string measuringBeam = "beam 2"; 

等等,梁的总数 – 八(8)。 所以MS Excel表格中每一行的格式必须是:

 ____________________________________________________________ | Current Date | Current Time | Measuring Beam | The Value | ------------------------------------------------------------ | 04.10.2016 | 09:21:54 | beam 1 | 347.25 | ------------------------------------------------------------ . . . . . . . . . . . . . and so on. . . . . . . . . . . . 

我认为在每个计时器中,应该创build下一行。 所以我需要以编程方式创build包含具有上述格式的表格的MS Excel文件,将该文件保存在特定文件夹中,然后在其中添加新行。 我认为提高出口率应该不是每行一行,而是每十行甚至每百行一行。 也就是说,一旦创build了下一百行,它就存储在Excel文件中。 整个导出操作将通过select相应的下拉菜单项以同样的方式停止。 每次导出启动时,都必须创build导出数据的新Excel文件。 在使用VSTO之前,我无法使用Excel对象模型。 但现在遇到这样的必要性。 我开始读MSDN的VSTO,但是由于创build我的应用程序,我非常拥挤。 请帮助创build导出到Excel。 好的榜样将是伟大的。 您的帮助将非常感激。

你不需要VSTO或互操作。 XLSX是一个压缩的XML文件集合,可以使用Open XML SDK或类似EPPLus的库来创build,您可以通过添加适当的NuGet包来简单地安装它。 如果你喜欢,你甚至可以自己生成XML文件,虽然像EPPlus这样的库使得这更容易。

您可以使用LoadFromDataTableLoadFromCollection类轻松地从数据表或强types列表生成Excel工作表,例如:

 using (ExcelPackage pck = new ExcelPackage()) { //Create the worksheet ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo"); //Load the datatable into the sheet, starting from cell A1. //Print the column names on row 1 //Apply the Dark1 style ws.Cells["A1"].LoadFromDataTable(tbl, true, TableStyles.Dark1); pck.SaveAs(new FileInfo(@"c:\temp\MyFile.xlsx")); } 

使用强types的集合同样简单:

  sheet.Cells["A1"].LoadFromCollection(items, true, TableStyles.Dark1); 

Excel工作表可以保存到任何stream。 [Web应用程序示例]显示了如何将程序包保存到Web应用程序的响应stream中,从而允许您创build真正的Excel文件,而不是具有假xlsx扩展名的CSV或HTML文件