如何从WPF MVVM应用程序导出日期时间,时间跨度,字符串和双精度值到Excel

本文关键字:字符串 时间跨度 双精度 Excel 时间 日期 WPF MVVM 应用程序 | 更新日期: 2023-09-27 18:11:20

在我的WPF MVVM Prism应用程序中,我每秒从外部设备读取一些数据(通过COM-port)(我使用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;

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

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

等,总梁数- 8(8)。因此,MS Excel表格中每行的格式必须为:

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

我认为在每个计时器滴答下一行应该被创建。因此,我需要以编程方式创建包含具有上述格式的表的MS Excel文件,将该文件保存在特定文件夹中,并在那里添加新行。我认为要提高导出率,不应该每一行保存一次,而应该每十行甚至每一百行保存一次。也就是说,一旦创建了接下来的100行,它就存储在Excel文件中。通过选择下拉菜单中相应的项来运行整个导出操作,并以相同的方式停止。每次导出启动时,都必须为导出的数据创建一个新的Excel文件。我以前没有使用Excel对象模型,也没有使用VSTO。但现在遇到这样的需要。我开始在MSDN中阅读关于VSTO的内容,但由于创建我的应用程序,我感到非常局促。请帮助创建出口到Excel。好榜样能激励伟人。我们将非常感激你的帮助。

如何从WPF MVVM应用程序导出日期时间,时间跨度,字符串和双精度值到Excel

您不需要VSTO或互操作。XLSX是XML文件的压缩集合,可以使用Open XML SDK或像EPPLus这样的库创建,只需添加适当的NuGet包即可安装。如果您愿意,您甚至可以自己生成XML文件,尽管像EPPlus这样的库使这更容易。

您可以使用LoadFromDataTableLoadFromCollection类轻松地从数据表或强类型列表生成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"));
}

使用强类型集合也很简单:

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

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

的CSV或HTML文件。