Files
kreta/Kreta.IntezmenyLetrehozo/Kreta.IntezmenyLetrehozo/ExcelTools/ExcelUtils.cs
T
2024-03-13 00:33:46 +01:00

296 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Kreta.IntezmenyLetrehozo
{
public static class ExcelUtils
{
#region Tulajdonságok
public const string ExcelVersion = "0.1";
const string versionNumberReference = "ZZ1";
public static string[] ColumnName = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ",
"BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ",
"CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ",
"DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ",
"EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ",
"FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ"};
#endregion
#region GetColumnNameIndex
public static uint GetColumnNameIndex(string colname)
{
uint index = 1;
foreach (var cname in ColumnName)
{
if (cname.Equals(colname))
{
break;
}
index++;
}
return index;
}
#endregion
#region GetColumnIndex
public static int GetColumnIndex(string reference)
{
int ci = 0;
reference = reference.ToUpper();
for (int ix = 0; ix < reference.Length && reference[ix] >= 'A'; ix++)
ci = (ci * 26) + ((int)reference[ix] - 64);
return ci;
}
#endregion
#region create cell in worksheet
// Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet.
// If the cell already exists, returns it.
// Given a Worksheet and a cell name, verifies that the specified cell exists.
// If it does not exist, creates a new cell.
public static Cell CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName)
{
string columnName = GetColumnName(cellName);
uint rowIndex = GetRowIndex(cellName);
Cell cell = new Cell();
IEnumerable<Row> rows = worksheet.Descendants<Row>().Where(r => r.RowIndex.Value == rowIndex);
// If the Worksheet does not contain the specified row, create the specified row.
// Create the specified cell in that row, and insert the row into the Worksheet.
if (rows.Count() == 0)
{
Row row = new Row() { RowIndex = new UInt32Value(rowIndex) };
cell = new Cell() { CellReference = new StringValue(cellName) };
row.Append(cell);
worksheet.Descendants<SheetData>().First().Append(row);
}
else
{
Row row = rows.First();
IEnumerable<Cell> cells = row.Elements<Cell>().Where(c => c.CellReference.Value == cellName);
// If the row does not contain the specified cell, create the specified cell.
if (cells.Count() == 0)
{
cell = new Cell() { CellReference = new StringValue(cellName) };
row.Append(cell);
}
}
return cell;
}
#endregion
#region InsertSharedStringItem
// Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text
// and inserts it into the SharedStringTablePart. If the item already exists, returns its index.
public static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart)
{
// If the part does not contain a SharedStringTable, create one.
if (shareStringPart.SharedStringTable == null)
{
shareStringPart.SharedStringTable = new SharedStringTable();
}
int i = 0;
// Iterate through all the items in the SharedStringTable. If the text already exists, return its index.
foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>())
{
if (item.InnerText == text)
{
return i;
}
i++;
}
// The text does not exist in the part. Create the SharedStringItem and return its index.
shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text)));
shareStringPart.SharedStringTable.Save();
return i;
}
#endregion
#region GetColumnName
// Given a cell name, parses the specified cell to get the column name.
public static string GetColumnName(string cellName)
{
// Create a regular expression to match the column name portion of the cell name.
Regex regex = new Regex("[A-Za-z]+");
Match match = regex.Match(cellName);
return match.Value;
}
#endregion
#region GetRowIndex
// Given a cell name, parses the specified cell to get the row index.
public static uint GetRowIndex(string cellName)
{
// Create a regular expression to match the row index portion the cell name.
Regex regex = new Regex(@"\d+");
Match match = regex.Match(cellName);
return uint.Parse(match.Value);
}
#endregion
#region GetCell
/// <summary>
/// Visszaadja oszlop nev es sor index alapjan az adott cellat.
/// </summary>
/// <param name="worksheet"></param>
/// <param name="columnName"></param>
/// <param name="rowIndex"></param>
/// <returns></returns>
public static Cell GetCell(Worksheet worksheet,
string columnName, uint rowIndex)
{
Row row = GetRow(worksheet, rowIndex);
if (row == null)
return null;
IEnumerable<Cell> cells = row.Elements<Cell>().Where(c => string.Compare
(c.CellReference.Value, columnName +
rowIndex, StringComparison.OrdinalIgnoreCase) == 0);
if (cells.Count() == 0)
return null;
return cells.First();
}
#endregion
#region GetCellValue
public static string GetCellValue(Worksheet worksheet, SharedStringTable table, string reference)
{
var cell = worksheet.Descendants<Cell>().Where(c => string.Compare(c.CellReference.Value, reference, StringComparison.OrdinalIgnoreCase) == 0).FirstOrDefault();
if (cell == null)
return null;
if (cell.DataType == CellValues.SharedString)
return table.ElementAt(int.Parse(cell.InnerText)).InnerText;
return cell.InnerText;
}
#endregion
#region GetRow
/// <summary>
/// Visszaadja a sor indexe alapjan az adott sor referenciajat.
/// </summary>
/// <param name="worksheet"></param>
/// <param name="rowIndex"></param>
/// <returns></returns>
public static Row GetRow(Worksheet worksheet, uint rowIndex)
{
IEnumerable<Row> myRows = worksheet.GetFirstChild<SheetData>().
Elements<Row>().Where(r => r.RowIndex == rowIndex);
if (myRows.Count() == 0)
return null;
return myRows.First();
}
#endregion
#region GetCellValue2
/// <summary>
/// Visszaadja a cella alapjan a hozza tartozo erteket a sharedstring tablabol.
/// </summary>
/// <param name="table"></param>
/// <param name="cell"></param>
/// <returns></returns>
public static string GetCellValue(SharedStringTable table, Cell cell)
{
int index = -1;
if (cell.CellValue == null)
return "";
if (cell.DataType != null && cell.DataType == CellValues.SharedString && Int32.TryParse(cell.CellValue.Text, out index))
{
return table.Elements<SharedStringItem>().ElementAt(index).InnerText;
}
return cell.CellValue.InnerText;
}
#endregion
#region SetColumns
/// <summary>
/// beallitja az oszlopokat, elso korben a bestfitet.
/// </summary>
public static void SetColumns(Worksheet sheet, int colindex, double maxcolcharacter, bool hidden)
{
// ha nem letezik hozza oszlopok tulajdonsag
Columns cols;
if (sheet.Descendants<Columns>().Count() == 0)
{
cols = new Columns();
sheet.Append(cols);
}
else
{
cols = sheet.Descendants<Columns>().First();
}
// oszlop letrehozasa, ahol elrejtjuk a validacios listat
double maxcolwidth = Math.Truncate(((maxcolcharacter * 7 + 5) / 7 * 256) / 256) + 2;
Column col = new Column()
{
Min = new UInt32Value((uint)colindex),
Max = new UInt32Value((uint)colindex),
Width = new DoubleValue(maxcolwidth),
Hidden = new BooleanValue(hidden),
BestFit = new BooleanValue(true),
CustomWidth = new BooleanValue(true)
};
cols.Append(col);
}
#endregion
#region Excel columns count
public static int GetColumnCount(Worksheet sheet)
{
var row = sheet.Descendants<Row>().FirstOrDefault();
if (row != null)
return row.Descendants<Cell>().Count();
return 0;
}
#endregion
#region SetVersion
public static void SetVersion(Worksheet sheet, string versionNumber)
{
// verzió
// uj cella
Cell newVersionCell = CreateSpreadsheetCellIfNotExist(sheet, versionNumberReference);
// majd index alapjan referenciat adok ra
var version = string.IsNullOrEmpty(versionNumber) == false ? versionNumber : ExcelVersion;
newVersionCell.CellValue = new CellValue(version);
// ez bizony egy sharedstring tipus
newVersionCell.DataType = new EnumValue<CellValues>(CellValues.String);
SetColumns(sheet, GetColumnIndex(versionNumberReference), 0, true);
}
#endregion
}
}