HRM-10/HRM.DA/DA/VirtualPaging/VirtualPagingExcel.cs
2026-11-09 16:39:51 +06:00

212 lines
9.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using HRM.BO;
namespace HRM.DA
{
/// <summary>
/// Export to Excel for &lt;app-virtual-grid&gt;: writes the rows of a data reader straight into an .xlsx
/// with the Open XML SAX writer (OpenXmlWriter), one row at a time. Fast and light on memory even for
/// very long lists, unlike building the workbook in the browser or as a full object model.
///
/// The file: a bold, frozen header row with filters, the grid's column titles and widths, dates as real
/// Excel dates ("dd mmm yyyy") and money as numbers ("#,##0.00"). Text is written as text, never as a formula.
/// </summary>
internal static class VirtualPagingExcel
{
private const int MaxRows = 1000000; // Excel's limit is 1,048,576
// Style indexes in the stylesheet below.
private const uint StyleHeader = 1, StyleDate = 2, StyleDateTime = 3, StyleMoney = 4;
internal static byte[] Create(IDataReader reader, List<VirtualPageColumn> columns)
{
// Columns to write: the grid's, or every field of the query when none were sent.
var fields = new List<ExcelColumn>();
if (columns.Count == 0)
{
for (int i = 0; i < reader.FieldCount; i++)
fields.Add(new ExcelColumn { Ordinal = i, Title = reader.GetName(i), Type = "text", Width = 15 });
}
else
{
foreach (VirtualPageColumn c in columns)
{
fields.Add(new ExcelColumn
{
Ordinal = reader.GetOrdinal(c.Field),
Title = string.IsNullOrWhiteSpace(c.Title) ? c.Field : c.Title,
Type = (c.Type ?? "text").ToLowerInvariant(),
Width = Math.Max(10, Math.Min(60, (c.Width > 0 ? c.Width : 130) / 7.0)),
});
}
}
using (var stream = new MemoryStream())
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = CreateStylesheet();
stylesPart.Stylesheet.Save();
WorksheetPart sheetPart = workbookPart.AddNewPart<WorksheetPart>();
int lastRow = WriteSheet(sheetPart, reader, fields);
string range = "$A$1:$" + ColumnName(fields.Count) + "$" + lastRow;
workbookPart.Workbook.AppendChild(new Sheets(
new Sheet { Id = workbookPart.GetIdOfPart(sheetPart), SheetId = 1U, Name = "Sheet1" }));
workbookPart.Workbook.AppendChild(new DefinedNames(
new DefinedName("'Sheet1'!" + range) { Name = "_xlnm._FilterDatabase", LocalSheetId = 0U, Hidden = true }));
workbookPart.Workbook.Save();
}
return stream.ToArray();
}
}
/// <summary>Header + every row, streamed. Returns the last row number.</summary>
private static int WriteSheet(WorksheetPart sheetPart, IDataReader reader, List<ExcelColumn> fields)
{
int rowIndex = 1;
using (OpenXmlWriter writer = OpenXmlWriter.Create(sheetPart))
{
writer.WriteStartElement(new Worksheet());
// Header row stays visible while scrolling.
writer.WriteElement(new SheetViews(new SheetView(
new Pane { VerticalSplit = 1D, TopLeftCell = "A2", ActivePane = PaneValues.BottomLeft, State = PaneStateValues.Frozen })
{ WorkbookViewId = 0U }));
writer.WriteStartElement(new Columns());
for (int i = 0; i < fields.Count; i++)
writer.WriteElement(new Column { Min = (uint)(i + 1), Max = (uint)(i + 1), Width = fields[i].Width, CustomWidth = true });
writer.WriteEndElement();
writer.WriteStartElement(new SheetData());
writer.WriteStartElement(new Row { RowIndex = 1U });
foreach (ExcelColumn f in fields)
writer.WriteElement(TextCell(f.Title, StyleHeader));
writer.WriteEndElement();
while (rowIndex <= MaxRows && reader.Read())
{
rowIndex++;
writer.WriteStartElement(new Row { RowIndex = (uint)rowIndex });
foreach (ExcelColumn f in fields)
writer.WriteElement(ValueCell(reader.IsDBNull(f.Ordinal) ? null : reader.GetValue(f.Ordinal), f.Type));
writer.WriteEndElement();
}
writer.WriteEndElement(); // SheetData
writer.WriteElement(new AutoFilter { Reference = "A1:" + ColumnName(fields.Count) + rowIndex });
writer.WriteEndElement(); // Worksheet
}
return rowIndex;
}
private static Cell ValueCell(object value, string type)
{
if (value == null)
return new Cell();
if (value is DateTime date && (type == "date" || type == "datetime"))
return new Cell { CellValue = new CellValue(date.ToOADate()), StyleIndex = type == "date" ? StyleDate : StyleDateTime };
if (IsNumber(value) && (type == "money" || type == "number"))
{
var cell = new Cell { CellValue = new CellValue(Convert.ToDecimal(value, CultureInfo.InvariantCulture)) };
if (type == "money")
cell.StyleIndex = StyleMoney;
return cell;
}
string text = value is DateTime d ? d.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)
: Convert.ToString(value, CultureInfo.InvariantCulture);
return TextCell(text, 0);
}
/// <summary>An inline text cell (never a formula). Characters XML cannot hold are dropped.</summary>
private static Cell TextCell(string text, uint style)
{
var cell = new Cell
{
DataType = CellValues.InlineString,
InlineString = new InlineString(new Text(CleanText(text)) { Space = SpaceProcessingModeValues.Preserve }),
};
if (style != 0)
cell.StyleIndex = style;
return cell;
}
private static Stylesheet CreateStylesheet()
{
return new Stylesheet(
new NumberingFormats(
new NumberingFormat { NumberFormatId = 164U, FormatCode = "dd mmm yyyy" },
new NumberingFormat { NumberFormatId = 165U, FormatCode = "dd mmm yyyy hh:mm" }) { Count = 2U },
new Fonts(
new Font(new FontSize { Val = 11D }, new FontName { Val = "Calibri" }),
new Font(new Bold(), new FontSize { Val = 11D }, new FontName { Val = "Calibri" })) { Count = 2U },
new Fills(
new Fill(new PatternFill { PatternType = PatternValues.None }),
new Fill(new PatternFill { PatternType = PatternValues.Gray125 }),
new Fill(new PatternFill(new ForegroundColor { Rgb = "FFE8ECF2" }) { PatternType = PatternValues.Solid })) { Count = 3U },
new Borders(new Border()) { Count = 1U },
new CellFormats(
new CellFormat(), // 0 default
new CellFormat { FontId = 1U, FillId = 2U, ApplyFont = true, ApplyFill = true }, // 1 header
new CellFormat { NumberFormatId = 164U, ApplyNumberFormat = true }, // 2 date
new CellFormat { NumberFormatId = 165U, ApplyNumberFormat = true }, // 3 date + time
new CellFormat { NumberFormatId = 4U, ApplyNumberFormat = true }) { Count = 5U }); // 4 money #,##0.00
}
private static bool IsNumber(object v) =>
v is decimal || v is double || v is float || v is int || v is long || v is short || v is byte;
private static string CleanText(string text)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
var sb = new StringBuilder(text.Length);
foreach (char ch in text)
{
if (ch == '\t' || ch == '\n' || ch == '\r' || ch >= 0x20 && ch != 0xFFFE && ch != 0xFFFF)
sb.Append(ch);
}
return sb.ToString();
}
/// <summary>1 → A, 27 → AA.</summary>
private static string ColumnName(int number)
{
string name = string.Empty;
while (number > 0)
{
int m = (number - 1) % 26;
name = (char)('A' + m) + name;
number = (number - 1) / 26;
}
return name;
}
private sealed class ExcelColumn
{
public int Ordinal;
public string Title;
public string Type;
public double Width;
}
}
}