Batch Export of Historical Data
A common request from engineers: Retrieve the historical data for key tags over the past N days and export it to Excel. The key is to break it down by time period.Transport in batches, Pulling data for 1 month at a time may cause a server timeout. Use C# + ClosedXML Example.
Sample Configuration
- Real-time updates CSV → End-to-end data collection to CSV
- Conceptual Background → Basics — Historical Models
Dependency
dotnet add package Darra.OpcUa
dotnet add package ClosedXML
ClosedXML It is an open-source library NET Excel that does not depend on Office.
Complete Code
using ClosedXML.Excel;
using DarraOpcUa_Client;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Replace with the PLC on-site industrial control computer IP; the remote server must have History access enabled (for the Darra PLC Server, the "History" option must be checked in the project).
const string endpoint = "opc.tcp://192.168.1.100:4840";
var nodes = new[]
{
"ns=2;s=Boiler1.Temperature",
"ns=2;s=Boiler1.Pressure",
};
var startUtc = DateTime.UtcNow.AddDays(-7);
var endUtc = DateTime.UtcNow;
var output = "history.xlsx";
using var ua = new DarraOpcUa(endpoint);
ua.Connect();
Console.WriteLine($"[OK] 已连接 {endpoint}");
using var workbook = new XLWorkbook();
foreach (var nodeId in nodes)
{
Console.WriteLine($"\n拉历史 {nodeId} [{startUtc:O} ~ {endUtc:O}]");
var sheet = workbook.Worksheets.Add(SafeSheetName(nodeId));
sheet.Cell(1, 1).Value = "SourceTimestamp(UTC)";
sheet.Cell(1, 2).Value = "Value";
sheet.Cell(1, 3).Value = "Status";
int row = 2;
// Divide the journey into 6-hour segments to avoid a single return trip that is too long.
foreach (var dv in PullByChunks(ua, nodeId, startUtc, endUtc, TimeSpan.FromHours(6)))
{
sheet.Cell(row, 1).Value = dv.SourceTimestamp ?? DateTime.MinValue;
sheet.Cell(row, 2).Value = dv.Value?.ToString();
sheet.Cell(row, 3).Value = dv.Status.ToString();
row++;
dv.Dispose();
}
sheet.Range("A1:C1").Style.Font.Bold = true;
sheet.Column(1).Width = 24;
Console.WriteLine($" 共 {row - 2} 行");
}
workbook.SaveAs(output);
Console.WriteLine($"\n已保存 {output}");
}
static IEnumerable<DataValue> PullByChunks(
DarraOpcUa ua, string nodeId, DateTime startUtc, DateTime endUtc, TimeSpan chunk)
{
var t = startUtc;
while (t < endUtc)
{
var t2 = (t + chunk) > endUtc ? endUtc : t + chunk;
IReadOnlyList<DataValue> dvs;
try { dvs = ua.ReadHistory(nodeId, t, t2, maxValues: 0); }
catch (OpcUaException ex)
{
Console.WriteLine($" [{t:HH:mm} ~ {t2:HH:mm}] 失败: {ex.StatusCode}");
t = t2;
continue;
}
foreach (var dv in dvs) yield return dv;
t = t2;
}
}
static string SafeSheetName(string nodeId)
{
var s = nodeId.Replace(":", "_").Replace(";", "_").Replace("/", "_");
return s.Length > 31 ? s.Substring(0, 31) : s; // Excel sheet name is limited to 31 characters
}
}
Code Highlights
- Divide the time period into 6-hour batches and process them sequentially; if a single batch is too large, the server may time out or reject it.
DataValueIt uses native memory, and historical data often runs into the tens of thousands of records, yet it doesn't run out of memory in a matter ofDisposeseconds.- Always use the following format for timestamps: UTC;
startUtc/endUtcUsing local time will cause errors in reports that span multiple time zones. - If a single segment fails (
OpcUaException), skip it and proceed to the next segment; do not let a local exception interrupt the entire export. - Excel Can't Open Data with Millions of Data Points Per Week → Modified
ReadHistoryProcessed+HistoryAggregate.Average+processingInterval: TimeSpan.FromHours(1)Aggregation; Only 168 Rows Per Hour Over 7 Days
Important Notes
- All timestamps UTC, Do not include the local time. Reports spanning multiple time zones will be calculated incorrectly.
BadHistoryOperationUnsupported= Historian is not installed on the server, so this node has no history. You can skip it.- The maximum number of rows in a single Excel sheet is approximately 104 ten-thousand rows; if you exceed this limit, you'll need to split the data across multiple sheets or split the file CSV.