kreta/Kreta.BusinessLogic/Classes/ExcelHelpers/ExcelManager.cs
2024-03-13 00:33:46 +01:00

2293 lines
114 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Kreta.Framework;
using a = DocumentFormat.OpenXml.Drawing;
namespace Kreta.BusinessLogic.Classes.ExcelHelpers
{
public class ExcelManager
{
private bool hasGridSubrow = false;
private Dictionary<string, int> _sharedstringtable = new Dictionary<string, int>(); // memóriában szedem össze a sztringeket, így gyorsabb (key=szöveg, value=index)
private Dictionary<uint, Row> _cellrows = new Dictionary<uint, Row>(); // memóriában tárolom az excel sorokat is, csak a végén adom hozzá
#region excel export
public string CreateExcelExport(string caption, ExcelDataSource DataSource, int SumLevelCount)
{
// eloszor is a cellak betoltese elott meghivom az export elkezdese esemenyt
BeginExcelExportCall(this, new OnBeginExcelExportHandlerEventArgs());
// megnezem, hogy hierarchikus-e a grid
if (SumLevelCount < 3)
{
hasGridSubrow = DataSource.Rows.Any(a => a.ChildDataSource != null) && KellMasodikSzint;
}
// excel fajl letrehozasa
if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/metabin/excel")))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/metabin/excel"));
}
string filename = HttpContext.Current.Server.MapPath("~/metabin/excel/") + Guid.NewGuid().ToString() + ".xlsx";
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
// Add workbook
WorkbookPart workbookPart = spreadSheet.AddWorkbookPart();
workbookPart.Workbook = new Workbook(new Sheets());
workbookPart.Workbook.Save();
WorksheetPart newWorksheetPart = InsertWorksheet(workbookPart, caption);
// Get the SharedStringTablePart. If it does not exist, create a new one.
SharedStringTablePart shareStringPart;
if (spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Any())
{
shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
}
else
{
shareStringPart = spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
}
// temak
ThemePart themePart = workbookPart.AddNewPart<ThemePart>();
GenerateThemePart().Save(themePart);
// stilusok
WorkbookStylesPart WorkbookstylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
GenerateWorkbookStylesPart().Save(WorkbookstylesPart);
//Ha a KellVedelem == true akkor rápakoljuk a lapvédelmet, egyébként nem
if (/*newWorksheetPart.Worksheet.Descendants<SheetProtection>().Count() == 0 && */KellVedelem)
{
string psswd = "bubuka";
using (System.Security.Cryptography.SHA1Managed oSHA = new System.Security.Cryptography.SHA1Managed())
{
psswd = Convert.ToBase64String(oSHA.ComputeHash(Encoding.UTF8.GetBytes(psswd)));
}
// lapvedelem
SheetProtection sheetProtection1 = new SheetProtection()
{
Password = psswd,
Sheet = true,
Objects = true,
Scenarios = true
};
newWorksheetPart.Worksheet.Append(sheetProtection1);
}
// Képletes oszlop hozzáadása
if (KepletesOszlopok != null && KepletesOszlopok.Count > 0)
{
foreach (KeyValuePair<string, Dictionary<string, string>> oszlopadatok in KepletesOszlopok)
{
ExcelDataSource.Column ujoszlop = new ExcelDataSource.Column();
ujoszlop.Name = oszlopadatok.Key;
ujoszlop.Value = oszlopadatok.Key;
ujoszlop.Type = ExcelDataSource.ColumnType.Formula;
string asd = ((Dictionary<string, string>)oszlopadatok.Value).First().Key;
int ujoszlophelye;
bool beszur; // beszúrunk-e (true) vagy hozzáadunk (false)
string oszlopnev = ((Dictionary<string, string>)oszlopadatok.Value).First().Key;
string keplet = ((Dictionary<string, string>)oszlopadatok.Value).First().Value;
if (!string.IsNullOrWhiteSpace(oszlopnev))
{
ujoszlophelye = Convert.ToInt32(GetColumnNameIndex(oszlopnev)) - 1;
if (ujoszlophelye > DataSource.Columns.Count - 1)
{
ujoszlophelye = DataSource.Columns.Count;
beszur = false;
}
else
{
beszur = true;
}
}
else
{
beszur = false;
ujoszlophelye = DataSource.Columns.Count;
}
if (beszur)
{
DataSource.Columns.Insert(ujoszlophelye, ujoszlop);
}
else
{
DataSource.Columns.Add(ujoszlop);
}
foreach (ExcelDataSource.Row sor in DataSource.Rows)
{
ExcelDataSource.Column ujcella = new ExcelDataSource.Column();
ujcella.Name = ujoszlop.Name;
ujcella.Value = keplet;
ujcella.Type = ExcelDataSource.ColumnType.Formula;
if (beszur)
{
sor.Cells.Insert(ujoszlophelye, ujcella);
}
else
{
sor.Cells.Add(ujcella);
}
}
}
}
// cellak felvetele
int rowIndex = 0;
if (SumLevelCount < 3)
{
InsertSimpleDataIntoCells(newWorksheetPart.Worksheet, shareStringPart, DataSource, ref rowIndex); // max 2 szintes export
}
else
{
IDColumnReference = "VV";
InsertMultipleLevelsDataIntoCells(newWorksheetPart.Worksheet, shareStringPart, DataSource); // min 3 szintes export
}
// a végén mentem a sharedstringtable-t, mert végrehajtás közben nagyon lassú
SaveSharedStringTable(shareStringPart);
// mentem a sorokat is
SaveExcelRows(newWorksheetPart.Worksheet);
}
return filename;
}
#region SetColumns
/// <summary>
/// beallitja az oszlopokat, elso korben a bestfitet.
/// </summary>
/// <param name="rowcount"></param>
void SetColumns(Worksheet sheet, int colindex, double maxcolcharacter)
{
// ha nem letezik hozza oszlopok tulajdonsag
Columns cols;
if (!sheet.Descendants<Columns>().Any())
{
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), BestFit = new BooleanValue(true), CustomWidth = new BooleanValue(true) };
cols.Append(col);
}
#endregion
#region Insert worksheet
// Given a WorkbookPart, inserts a new worksheet.
private WorksheetPart InsertWorksheet(WorkbookPart workbookPart, string SheetName)
{
// Add a new worksheet part to the workbook.
WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new Columns(), new SheetData());
newWorksheetPart.Worksheet.Save();
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new sheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Any())
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Append the new worksheet and associate it with the workbook.
//eltávolítjuk a nem meg felelő charaktereket a sheetNameből
//{ '.', '?', '!', '*', '/', '[', ']', '\'', ':' };
if (string.IsNullOrWhiteSpace(SheetName))
{
// ha nincs benne szoveg, akkor bele kell tenni, mert kulonben elszall
SheetName = "Neptun export";
}
SheetName = new Regex(@"[\.,\?,\!,\*,\/,\[,\],\\,\:]").Replace(SheetName, "");
if (SheetName.Length > 30)
{
SheetName = SheetName.Substring(0, 30);
}
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = SheetName };
sheets.Append(sheet);
workbookPart.Workbook.Save();
return newWorksheetPart;
}
#endregion
#region InsertStyles
private Stylesheet GenerateWorkbookStylesPart()
{
var element =
new Stylesheet(
new Fonts(
new Font(
new FontSize() { Val = 11D },
new Color() { Theme = (UInt32Value)1U },
new FontName() { Val = "Calibri" },
new FontFamilyNumbering() { Val = 2 },
new FontCharSet() { Val = 238 },
new FontScheme() { Val = FontSchemeValues.Minor }),
new Font(
new Bold(),
new FontSize() { Val = 11D },
new Color() { Theme = (UInt32Value)1U },
new FontName() { Val = "Calibri" },
new FontFamilyNumbering() { Val = 2 },
new FontCharSet() { Val = 238 },
new FontScheme() { Val = FontSchemeValues.Minor })
)
{ Count = (UInt32Value)2U },
new Fills(
new Fill(
new PatternFill() { PatternType = PatternValues.None }),
new Fill(
new PatternFill() { PatternType = PatternValues.Gray125 }),
new Fill(
new PatternFill(
new ForegroundColor() { Theme = (UInt32Value)0U, Tint = new DoubleValue() { InnerText = "-0.249977111117893" } },
new BackgroundColor() { Indexed = (UInt32Value)64U }
)
{ PatternType = PatternValues.Solid }),
new Fill(
new PatternFill(
new ForegroundColor() { Theme = (UInt32Value)2U },
new BackgroundColor() { Indexed = (UInt32Value)64U }
)
{ PatternType = PatternValues.Solid }),
new Fill(
new PatternFill(
new ForegroundColor() { Theme = (UInt32Value)0U },
new BackgroundColor() { Indexed = (UInt32Value)64U }
)
{ PatternType = PatternValues.Solid })
)
{ Count = (UInt32Value)5U },
new Borders(
new Border(
new LeftBorder(),
new RightBorder(),
new TopBorder(),
new BottomBorder(),
new DiagonalBorder()),
new Border(
new LeftBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new RightBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new TopBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new BottomBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new DiagonalBorder()),
new Border(
new LeftBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new RightBorder(),
new TopBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new BottomBorder(),
new DiagonalBorder()),
new Border(
new LeftBorder(),
new RightBorder(),
new TopBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new BottomBorder(),
new DiagonalBorder()),
new Border(
new LeftBorder(),
new RightBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new TopBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new BottomBorder(),
new DiagonalBorder()),
new Border(
new LeftBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new RightBorder(),
new TopBorder(),
new BottomBorder(),
new DiagonalBorder()),
new Border(
new LeftBorder(),
new RightBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new TopBorder(),
new BottomBorder(),
new DiagonalBorder()),
new Border(
new LeftBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new RightBorder(),
new TopBorder(),
new BottomBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new DiagonalBorder()),
new Border(
new LeftBorder(),
new RightBorder(),
new TopBorder(),
new BottomBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new DiagonalBorder()),
new Border(
new LeftBorder(),
new RightBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new TopBorder(),
new BottomBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new DiagonalBorder()),
new Border(
new LeftBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new RightBorder(),
new TopBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new BottomBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new DiagonalBorder()),
new Border(
new LeftBorder(),
new RightBorder(),
new TopBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new BottomBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new DiagonalBorder()),
new Border(
new LeftBorder(),
new RightBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new TopBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new BottomBorder(
new Color() { Auto = true }
)
{ Style = BorderStyleValues.Thin },
new DiagonalBorder())
)
{ Count = (UInt32Value)13U },
new CellStyleFormats(
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U }
)
{ Count = (UInt32Value)1U },
new CellFormats( // nem irhato cellak
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFont = true, ApplyFill = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)3U, BorderId = (UInt32Value)3U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyBorder = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)3U, BorderId = (UInt32Value)8U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyBorder = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)3U, BorderId = (UInt32Value)11U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyBorder = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)3U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)8U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyNumberFormat = true, ApplyProtection = true },
// irhato cellak (feher hatter, fekete kerettel)
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFont = true, ApplyFill = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)4U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyBorder = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)4U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyBorder = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)4U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyBorder = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)4U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyNumberFormat = true, ApplyProtection = true },
new CellFormat() { NumberFormatId = (UInt32Value)49U, FontId = (UInt32Value)0U, FillId = (UInt32Value)4U, BorderId = (UInt32Value)1U, FormatId = (UInt32Value)0U, Protection = new Protection() { Locked = false }, ApplyFill = true, ApplyNumberFormat = true, ApplyProtection = true },
// Formula, nem módosítható
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)3U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyProtection = true }
)
{ Count = (UInt32Value)14U },
new CellStyles(
new CellStyle() { Name = "Normál", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U }
)
{ Count = (UInt32Value)1U },
new DifferentialFormats() { Count = (UInt32Value)0U },
new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium9", DefaultPivotStyle = "PivotStyleLight16" },
new Colors(
new MruColors(
new Color() { Rgb = new HexBinaryValue() { Value = "FF969696" } })));
return element;
}
#endregion
#region Themes
private a.Theme GenerateThemePart()
{
var element =
new a.Theme(
new a.ThemeElements(
new a.ColorScheme(
new a.Dark1Color(
new a.SystemColor() { Val = a.SystemColorValues.WindowText, LastColor = new HexBinaryValue() { Value = "000000" } }),
new a.Light1Color(
new a.SystemColor() { Val = a.SystemColorValues.Window, LastColor = new HexBinaryValue() { Value = "FFFFFF" } }),
new a.Dark2Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "1F497D" } }),
new a.Light2Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "EEECE1" } }),
new a.Accent1Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "4F81BD" } }),
new a.Accent2Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "C0504D" } }),
new a.Accent3Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "9BBB59" } }),
new a.Accent4Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "8064A2" } }),
new a.Accent5Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "4BACC6" } }),
new a.Accent6Color(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "F79646" } }),
new a.Hyperlink(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "0000FF" } }),
new a.FollowedHyperlinkColor(
new a.RgbColorModelHex() { Val = new HexBinaryValue() { Value = "800080" } })
)
{ Name = "Office" },
new a.FontScheme(
new a.MajorFont(
new a.LatinFont() { Typeface = "Cambria" },
new a.EastAsianFont() { Typeface = "" },
new a.ComplexScriptFont() { Typeface = "" },
new a.SupplementalFont() { Script = "Arab", Typeface = "Times New Roman" },
new a.SupplementalFont() { Script = "Hebr", Typeface = "Times New Roman" },
new a.SupplementalFont() { Script = "Thai", Typeface = "Tahoma" },
new a.SupplementalFont() { Script = "Ethi", Typeface = "Nyala" },
new a.SupplementalFont() { Script = "Beng", Typeface = "Vrinda" },
new a.SupplementalFont() { Script = "Gujr", Typeface = "Shruti" },
new a.SupplementalFont() { Script = "Khmr", Typeface = "MoolBoran" },
new a.SupplementalFont() { Script = "Knda", Typeface = "Tunga" },
new a.SupplementalFont() { Script = "Guru", Typeface = "Raavi" },
new a.SupplementalFont() { Script = "Cans", Typeface = "Euphemia" },
new a.SupplementalFont() { Script = "Cher", Typeface = "Plantagenet Cherokee" },
new a.SupplementalFont() { Script = "Yiii", Typeface = "Microsoft Yi Baiti" },
new a.SupplementalFont() { Script = "Tibt", Typeface = "Microsoft Himalaya" },
new a.SupplementalFont() { Script = "Thaa", Typeface = "MV Boli" },
new a.SupplementalFont() { Script = "Deva", Typeface = "Mangal" },
new a.SupplementalFont() { Script = "Telu", Typeface = "Gautami" },
new a.SupplementalFont() { Script = "Taml", Typeface = "Latha" },
new a.SupplementalFont() { Script = "Syrc", Typeface = "Estrangelo Edessa" },
new a.SupplementalFont() { Script = "Orya", Typeface = "Kalinga" },
new a.SupplementalFont() { Script = "Mlym", Typeface = "Kartika" },
new a.SupplementalFont() { Script = "Laoo", Typeface = "DokChampa" },
new a.SupplementalFont() { Script = "Sinh", Typeface = "Iskoola Pota" },
new a.SupplementalFont() { Script = "Mong", Typeface = "Mongolian Baiti" },
new a.SupplementalFont() { Script = "Viet", Typeface = "Times New Roman" },
new a.SupplementalFont() { Script = "Uigh", Typeface = "Microsoft Uighur" }),
new a.MinorFont(
new a.LatinFont() { Typeface = "Calibri" },
new a.EastAsianFont() { Typeface = "" },
new a.ComplexScriptFont() { Typeface = "" },
new a.SupplementalFont() { Script = "Arab", Typeface = "Arial" },
new a.SupplementalFont() { Script = "Hebr", Typeface = "Arial" },
new a.SupplementalFont() { Script = "Thai", Typeface = "Tahoma" },
new a.SupplementalFont() { Script = "Ethi", Typeface = "Nyala" },
new a.SupplementalFont() { Script = "Beng", Typeface = "Vrinda" },
new a.SupplementalFont() { Script = "Gujr", Typeface = "Shruti" },
new a.SupplementalFont() { Script = "Khmr", Typeface = "DaunPenh" },
new a.SupplementalFont() { Script = "Knda", Typeface = "Tunga" },
new a.SupplementalFont() { Script = "Guru", Typeface = "Raavi" },
new a.SupplementalFont() { Script = "Cans", Typeface = "Euphemia" },
new a.SupplementalFont() { Script = "Cher", Typeface = "Plantagenet Cherokee" },
new a.SupplementalFont() { Script = "Yiii", Typeface = "Microsoft Yi Baiti" },
new a.SupplementalFont() { Script = "Tibt", Typeface = "Microsoft Himalaya" },
new a.SupplementalFont() { Script = "Thaa", Typeface = "MV Boli" },
new a.SupplementalFont() { Script = "Deva", Typeface = "Mangal" },
new a.SupplementalFont() { Script = "Telu", Typeface = "Gautami" },
new a.SupplementalFont() { Script = "Taml", Typeface = "Latha" },
new a.SupplementalFont() { Script = "Syrc", Typeface = "Estrangelo Edessa" },
new a.SupplementalFont() { Script = "Orya", Typeface = "Kalinga" },
new a.SupplementalFont() { Script = "Mlym", Typeface = "Kartika" },
new a.SupplementalFont() { Script = "Laoo", Typeface = "DokChampa" },
new a.SupplementalFont() { Script = "Sinh", Typeface = "Iskoola Pota" },
new a.SupplementalFont() { Script = "Mong", Typeface = "Mongolian Baiti" },
new a.SupplementalFont() { Script = "Viet", Typeface = "Arial" },
new a.SupplementalFont() { Script = "Uigh", Typeface = "Microsoft Uighur" })
)
{ Name = "Office" },
new a.FormatScheme(
new a.FillStyleList(
new a.SolidFill(
new a.SchemeColor() { Val = a.SchemeColorValues.PhColor }),
new a.GradientFill(
new a.GradientStopList(
new a.GradientStop(
new a.SchemeColor(
new a.Tint() { Val = 50000 },
new a.SaturationModulation() { Val = 300000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 0 },
new a.GradientStop(
new a.SchemeColor(
new a.Tint() { Val = 37000 },
new a.SaturationModulation() { Val = 300000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 35000 },
new a.GradientStop(
new a.SchemeColor(
new a.Tint() { Val = 15000 },
new a.SaturationModulation() { Val = 350000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 100000 }),
new a.LinearGradientFill() { Angle = 16200000, Scaled = true }
)
{ RotateWithShape = true },
new a.GradientFill(
new a.GradientStopList(
new a.GradientStop(
new a.SchemeColor(
new a.Shade() { Val = 51000 },
new a.SaturationModulation() { Val = 130000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 0 },
new a.GradientStop(
new a.SchemeColor(
new a.Shade() { Val = 93000 },
new a.SaturationModulation() { Val = 130000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 80000 },
new a.GradientStop(
new a.SchemeColor(
new a.Shade() { Val = 94000 },
new a.SaturationModulation() { Val = 135000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 100000 }),
new a.LinearGradientFill() { Angle = 16200000, Scaled = false }
)
{ RotateWithShape = true }),
new a.LineStyleList(
new a.Outline(
new a.SolidFill(
new a.SchemeColor(
new a.Shade() { Val = 95000 },
new a.SaturationModulation() { Val = 105000 }
)
{ Val = a.SchemeColorValues.PhColor }),
new a.PresetDash() { Val = a.PresetLineDashValues.Solid }
)
{ Width = 9525, CapType = a.LineCapValues.Flat, CompoundLineType = a.CompoundLineValues.Single, Alignment = a.PenAlignmentValues.Center },
new a.Outline(
new a.SolidFill(
new a.SchemeColor() { Val = a.SchemeColorValues.PhColor }),
new a.PresetDash() { Val = a.PresetLineDashValues.Solid }
)
{ Width = 25400, CapType = a.LineCapValues.Flat, CompoundLineType = a.CompoundLineValues.Single, Alignment = a.PenAlignmentValues.Center },
new a.Outline(
new a.SolidFill(
new a.SchemeColor() { Val = a.SchemeColorValues.PhColor }),
new a.PresetDash() { Val = a.PresetLineDashValues.Solid }
)
{ Width = 38100, CapType = a.LineCapValues.Flat, CompoundLineType = a.CompoundLineValues.Single, Alignment = a.PenAlignmentValues.Center }),
new a.EffectStyleList(
new a.EffectStyle(
new a.EffectList(
new a.OuterShadow(
new a.RgbColorModelHex(
new a.Alpha() { Val = 38000 }
)
{ Val = new HexBinaryValue() { Value = "000000" } }
)
{ BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
new a.EffectStyle(
new a.EffectList(
new a.OuterShadow(
new a.RgbColorModelHex(
new a.Alpha() { Val = 35000 }
)
{ Val = new HexBinaryValue() { Value = "000000" } }
)
{ BlurRadius = 40000L, Distance = 23000L, Direction = 5400000, RotateWithShape = false })),
new a.EffectStyle(
new a.EffectList(
new a.OuterShadow(
new a.RgbColorModelHex(
new a.Alpha() { Val = 35000 }
)
{ Val = new HexBinaryValue() { Value = "000000" } }
)
{ BlurRadius = 40000L, Distance = 23000L, Direction = 5400000, RotateWithShape = false }),
new a.Scene3DType(
new a.Camera(
new a.Rotation() { Latitude = 0, Longitude = 0, Revolution = 0 }
)
{ Preset = a.PresetCameraValues.OrthographicFront },
new a.LightRig(
new a.Rotation() { Latitude = 0, Longitude = 0, Revolution = 1200000 }
)
{ Rig = a.LightRigValues.ThreePoints, Direction = a.LightRigDirectionValues.Top }),
new a.Shape3DType(
new a.BevelTop() { Width = 63500L, Height = 25400L }))),
new a.BackgroundFillStyleList(
new a.SolidFill(
new a.SchemeColor() { Val = a.SchemeColorValues.PhColor }),
new a.GradientFill(
new a.GradientStopList(
new a.GradientStop(
new a.SchemeColor(
new a.Tint() { Val = 40000 },
new a.SaturationModulation() { Val = 350000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 0 },
new a.GradientStop(
new a.SchemeColor(
new a.Tint() { Val = 45000 },
new a.Shade() { Val = 99000 },
new a.SaturationModulation() { Val = 350000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 40000 },
new a.GradientStop(
new a.SchemeColor(
new a.Shade() { Val = 20000 },
new a.SaturationModulation() { Val = 255000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 100000 }),
new a.PathGradientFill(
new a.FillToRectangle() { Left = 50000, Top = -80000, Right = 50000, Bottom = 180000 }
)
{ Path = a.PathShadeValues.Circle }
)
{ RotateWithShape = true },
new a.GradientFill(
new a.GradientStopList(
new a.GradientStop(
new a.SchemeColor(
new a.Tint() { Val = 80000 },
new a.SaturationModulation() { Val = 300000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 0 },
new a.GradientStop(
new a.SchemeColor(
new a.Shade() { Val = 30000 },
new a.SaturationModulation() { Val = 200000 }
)
{ Val = a.SchemeColorValues.PhColor }
)
{ Position = 100000 }),
new a.PathGradientFill(
new a.FillToRectangle() { Left = 50000, Top = 50000, Right = 50000, Bottom = 50000 }
)
{ Path = a.PathShadeValues.Circle }
)
{ RotateWithShape = true })
)
{ Name = "Office" }),
new a.ObjectDefaults(),
new a.ExtraColorSchemeList()
)
{ Name = "Office-téma" };
return element;
}
#endregion
#region InsertDataIntoCells
Dictionary<int, int> _ColumnMaxCharacterCount = new Dictionary<int, int>(); // ebben szamolom ki, hogy hany karakter lehet oszloponkent maximum
/// <summary>
/// Felveszem az adatokat a cellakba.
///
/// Ez a régi működés. Ez van használva a maximum 2 szintes exportra.
/// </summary>
/// <param name="rootNode"></param>
private void InsertSimpleDataIntoCells(Worksheet sheet, SharedStringTablePart SharedstringPart, ExcelDataSource datasource, ref int refrowIndex)
{
int excelrowIndex = 1;
bool issubrow = refrowIndex > 0; // ez 2.szintu sor
// checkbox validacios lista
StringBuilder validchklistcolumns = new StringBuilder(); // ebben azok a cellak vannak, amikre majd validacios listat akarunk allitani
StringBuilder refchkvalidlistcolumns = new StringBuilder(); // ebben azoknak a cellak a referenciai vannak, amiket a 2.szint befejezese utan tovabb tudunk folytatni pl.: C{0}:C{1} - {0} sor kezdete, {1} sor vege
// combobox validacios lista
Dictionary<string, StringBuilder> validcmblistcolumnsByColName = new Dictionary<string, StringBuilder>(); // ebben azok a cellak vannak, amikre majd validacios listat akarunk allitani
StringBuilder refcmbvalidlistcolumns = new StringBuilder(); // ebben azoknak a cellak a referenciai vannak, amiket a 2.szint befejezese utan tovabb tudunk folytatni pl.: C{0}:C{1} - {0} sor kezdete, {1} sor vege
// elmentem elore az elrejteni kivant oszlopokat, mivel mindenkeppen csak sorrendben lehet hozzaadni a columns-k listahoz
List<string> _hiddenColumnNames = new List<string>();
#region fejlec
int excelcolIndex = 0;
if (issubrow)
{
excelcolIndex = 1;
}
int headersharedindex = 0;
for (int sourcecolIndex = 0; sourcecolIndex < datasource.Columns.Count; sourcecolIndex++)
{
var datasourceCol = datasource.Columns[sourcecolIndex];
// cella referencia
string cellreference = GetExtendedColumName(excelcolIndex) + (refrowIndex + excelrowIndex).ToString();
// uj cella (TD)
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
// szoveg objektum letrehozasa
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
headersharedindex = InsertSharedStringItem(datasourceCol.Value);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(headersharedindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, excelrowIndex, excelcolIndex, datasource.Rows.Count, datasource.Columns.Count, false, issubrow, false);
// maximalis karakter szamolas
if (!_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
|| (_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
&& _ColumnMaxCharacterCount[excelcolIndex + 1] < datasourceCol.Value.Length))
{
_ColumnMaxCharacterCount[excelcolIndex + 1] = datasourceCol.Value.Length;
}
excelcolIndex++;
}
// header ID cella
// cella referencia
Cell newCellID = CreateSpreadsheetCellIfNotExist(sheet, IDColumnReference + (refrowIndex + excelrowIndex).ToString());
int IDindex = InsertSharedStringItem("");
// majd index alapjan referenciat adok ra
newCellID.CellValue = new CellValue(IDindex.ToString());
// ez bizony egy sharedstring tipus
newCellID.DataType = new EnumValue<CellValues>(CellValues.SharedString);
newCellID.StyleIndex = (UInt32Value)1U;
#endregion
excelrowIndex++;
for (int sourcerowIndex = 0; sourcerowIndex < datasource.Rows.Count; sourcerowIndex++)
{
ExcelDataSource.Row datasourceRow = datasource.Rows[sourcerowIndex];
bool hassubrow = false; // 1.szintu, de van 2.szintu sora
// uj sor (TR)
#region Cellak
excelcolIndex = 0;
if (issubrow)
{
excelcolIndex = 1;
}
foreach (var cell in datasourceRow.Cells)
{
if (GetExtendedColumName(excelcolIndex) == IDColumnReference)
{
continue;
}
int sharedindex = 0;
// cella referencia
string cellreference = GetExtendedColumName(excelcolIndex) + (refrowIndex + excelrowIndex).ToString();
// uj cella (TD)
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
string cellText = cell.Value;
var datatype = datasource.Columns.Where(a => a.Name == cell.Name).Select(a => a.Type).First();
switch (datatype)
{
case ExcelDataSource.ColumnType.Formula:
case ExcelDataSource.ColumnType.String:
// szoveg
// szoveg objektum letrehozasa
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
sharedindex = InsertSharedStringItem(cellText);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(sharedindex.ToString());
if (datatype == ExcelDataSource.ColumnType.String)
{
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// maximalis karakter szamolas
if (!_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
|| (_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
&& _ColumnMaxCharacterCount[excelcolIndex + 1] < cellText.Length))
{
_ColumnMaxCharacterCount[excelcolIndex + 1] = cellText.Length;
}
// beallitom a cella stilusat
SetStyleIndex(newCell, excelrowIndex, excelcolIndex, datasource.Rows.Count, datasource.Columns.Count, hassubrow, issubrow, false);
}
else
{
newCell.CellFormula = new CellFormula(cellText.Replace("{0}", excelrowIndex.ToString()));
// Nem módosítható stílus
newCell.StyleIndex = (UInt32Value)14U;
}
break;
case ExcelDataSource.ColumnType.Combo:
sharedindex = InsertSharedStringItem(cellText);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(sharedindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, excelrowIndex, excelcolIndex, datasource.Rows.Count, datasource.Columns.Count, hassubrow, issubrow, false);
// maximalis karakter szamolas
if (!_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
|| (_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
&& _ColumnMaxCharacterCount[excelcolIndex + 1] < cellText.Length))
{
_ColumnMaxCharacterCount[excelcolIndex + 1] = cellText.Length;
}
// ha combobox tipusu
// akkor megjegyzem a cellat es kesobb rahuzok egy validacios listat
if (cell.ComboDataSource.Rows.Count > 0)
{
// csak akkor vegyek fel validacios listat, ha vannak hozza ertekek
if (!validcmblistcolumnsByColName.ContainsKey(cell.Name))
{
// ha még nincs, akkor létrehozom
validcmblistcolumnsByColName.Add(cell.Name, new StringBuilder());
}
if (excelrowIndex == 2)
{
if (!issubrow)
{
// ha 1. szintu, akkor csak addig lehet sorfolytonosan validacios listat
// rahuzni a sorokra, amig meg nem szakitja egy 2.szintu sor
// ezekutan csak akkor lehet folytatni, ha vege a 2.szintnek!
refcmbvalidlistcolumns.AppendFormat("{0}{1}:{0}{2} ", GetExtendedColumName(excelcolIndex), "{0}", "{1}");
validcmblistcolumnsByColName[cell.Name].AppendFormat("{0}2:{0}",
GetExtendedColumName(excelcolIndex)).Append("{0} ");
}
else
{
// 2. szintu sorok, itt biztosan nem szakitja meg semmi a fol
int startrowindex = refrowIndex + excelrowIndex;
int endrowindex = startrowindex + datasource.Rows.Count - 2;
validcmblistcolumnsByColName[cell.Name].AppendFormat("{0}{1}:{0}{2} ", GetExtendedColumName(excelcolIndex),
startrowindex.ToString(), endrowindex.ToString());
}
}
// beallitom a cella stilusat
SetStyleIndex(newCell, excelrowIndex, excelcolIndex, datasource.Rows.Count, datasource.Columns.Count, hassubrow, issubrow, KellVedelem);
}
break;
case ExcelDataSource.ColumnType.Checkbox:
// checkbox
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, excelrowIndex, excelcolIndex, datasource.Rows.Count, datasource.Columns.Count, hassubrow, issubrow, KellVedelem);
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
sharedindex = 0;
if (string.IsNullOrWhiteSpace(cellText))
{
sharedindex = InsertSharedStringItem(StringResourcesUtil.GetString(134)/*Nem*/);
}
else
{
bool ertek = false;
bool isvalid = bool.TryParse(cellText, out ertek);
if (!isvalid)
{
ertek = cellText.Trim() == "1";
}
if (ertek)
{
sharedindex = InsertSharedStringItem(StringResourcesUtil.GetString(133)/*Igen*/);
}
else
{
sharedindex = InsertSharedStringItem(StringResourcesUtil.GetString(134)/*Nem*/);
}
}
newCell.CellValue = new CellValue(sharedindex.ToString());
if (excelrowIndex == 2)
{
if (!issubrow)
{
// ha 1. szintu, akkor csak addig lehet sorfolytonosan validacios listat
// rahuzni a sorokra, amig meg nem szakitja egy 2.szintu sor
// ezekutan csak akkor lehet folytatni, ha vege a 2.szintnek!
refchkvalidlistcolumns.AppendFormat("{0}{1}:{0}{2} ", GetExtendedColumName(excelcolIndex), "{0}", "{1}");
validchklistcolumns.AppendFormat("{0}2:{0}",
GetExtendedColumName(excelcolIndex)).Append("{0} ");
}
else
{
// 2. szintu sorok, itt biztosan nem szakitja meg semmi a fol
int startrowindex = refrowIndex + excelrowIndex;
int endrowindex = startrowindex + datasource.Rows.Count - 2;
validchklistcolumns.AppendFormat("{0}{1}:{0}{2} ", GetExtendedColumName(excelcolIndex),
startrowindex.ToString(), endrowindex.ToString());
}
}
break;
}
excelcolIndex++;
}
if (UserExcelCells != null && UserExcelCells.Count > 0)
{
if (UserExcelCells.Keys.First()[0] > IDColumnReference[0])
{
// ha a felhasznalo altal kert plusz mezok kesobbiek, mint a kert ID mezo, akkor eloszor az IDkat vesszuk fel
// ID elmentese
InsertIDColumns(datasourceRow, sheet, SharedstringPart, _hiddenColumnNames, excelrowIndex, refrowIndex);
// utana johet a kert mezok
InsertUserCellsValues(sheet, SharedstringPart, excelrowIndex);
// Zsolt
if (datasource.Rows.Count == 1)
{
InsertUserCellsValues(sheet, SharedstringPart, excelrowIndex + 1);
}
}
else
{
// ha a felhasznalo altal kert plusz mezok elobbiek, mint a kert ID mezo, akkor eloszor a kert mezoket vesszuk fel
InsertUserCellsValues(sheet, SharedstringPart, excelrowIndex);
// Zsolt
if (datasource.Rows.Count == 1)
{
InsertUserCellsValues(sheet, SharedstringPart, excelrowIndex + 1);
}
// utana johet az ID elmentese
InsertIDColumns(datasourceRow, sheet, SharedstringPart, _hiddenColumnNames, excelrowIndex, refrowIndex);
}
}
else
{
// ha nincs kert mezo, akkor siman az ID mentese jon
InsertIDColumns(datasourceRow, sheet, SharedstringPart, _hiddenColumnNames, excelrowIndex, refrowIndex);
}
// meg kell vizsgalni, hogy ez olyan 1.szintu tetel, aminek van-e 2.szintu sora
// nem header es nem 2.szintu sor
if (KellMasodikSzint && datasourceRow.ChildDataSource != null && datasourceRow.ChildDataSource.Rows != null && !issubrow)
{
hassubrow = true;
// ha volt validacios oszlop, akkor azt a 2.szint kezdete elott le kell zarni
// chk
string refstring = string.Format(validchklistcolumns.ToString(), excelrowIndex.ToString());
validchklistcolumns.Length = 0;
validchklistcolumns.AppendFormat(refstring);
// cmb
if (validcmblistcolumnsByColName.Count > 0)
{
refstring = string.Format(validcmblistcolumnsByColName.Last().Value.ToString(), excelrowIndex.ToString());
validcmblistcolumnsByColName.Last().Value.Length = 0;
validcmblistcolumnsByColName.Last().Value.AppendFormat(refstring);
}
// meghivom a 2.szintre a feldolgozast
InsertSimpleDataIntoCells(sheet, SharedstringPart, datasourceRow.ChildDataSource, ref excelrowIndex);
// ha volt validacios oszlop, akkor azt a 2.szint utan folytatni kell
if (sourcerowIndex + 1 < datasource.Rows.Count) // csak akkor kell, ha van meg sor
{
validchklistcolumns.AppendFormat(refchkvalidlistcolumns.ToString(), (excelrowIndex + 1).ToString(), "{0}");
if (validcmblistcolumnsByColName.Count > 0)
{
validcmblistcolumnsByColName.Last().Value.AppendFormat(refcmbvalidlistcolumns.ToString(), (excelrowIndex + 1).ToString(), "{0}");
}
}
}
// ha van plusz subitems, akkor kulon sorban
if (datasourceRow.RowSubItems != null)
{
// ha volt validacios oszlop, akkor azt a subitem szint kezdete elott le kell zarni
// chk
string refstring = string.Format(validchklistcolumns.ToString(), excelrowIndex.ToString());
validchklistcolumns.Length = 0;
validchklistcolumns.AppendFormat(refstring);
// cmb
if (validcmblistcolumnsByColName.Count > 0)
{
refstring = string.Format(validcmblistcolumnsByColName.Last().Value.ToString(), excelrowIndex.ToString());
validcmblistcolumnsByColName.Last().Value.Length = 0;
validcmblistcolumnsByColName.Last().Value.AppendFormat(refstring);
}
// felveszek egy plusz sort az itemekkel
excelrowIndex++;
excelcolIndex = 1;
foreach (var subitem in datasourceRow.RowSubItems)
{
int sharedindex = 0;
// cella referencia
string cellreference = GetExtendedColumName(excelcolIndex) + (excelrowIndex).ToString();
// uj cella (TD)
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
string cellText = subitem.Value;
// szoveg
// szoveg objektum letrehozasa
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
sharedindex = InsertSharedStringItem(cellText);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(sharedindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, 2, excelcolIndex, datasource.Rows.Count, datasource.Columns.Count, false, false, false);
// maximalis karakter szamolas
if (!_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
|| (_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
&& _ColumnMaxCharacterCount[excelcolIndex + 1] < cellText.Length))
{
_ColumnMaxCharacterCount[excelcolIndex + 1] = cellText.Length;
}
excelcolIndex++;
}
// ha volt validacios oszlop, akkor azt a 2.szint utan folytatni kell
if (sourcerowIndex + 1 < datasource.Rows.Count) // csak akkor kell, ha van meg sor
{
validchklistcolumns.AppendFormat(refchkvalidlistcolumns.ToString(), (excelrowIndex + 1).ToString(), "{0}");
if (validcmblistcolumnsByColName.Count > 0)
{
validcmblistcolumnsByColName.Last().Value.AppendFormat(refcmbvalidlistcolumns.ToString(), (excelrowIndex + 1).ToString(), "{0}");
}
}
}
excelrowIndex++;
}
#endregion
if (UserExcelColumns != null)
{
// ha el kell egy oszlopot tuntetni, akkor felveszem azok koze
foreach (var colname in this.UserExcelColumns.Keys)
{
bool hidden = UserExcelColumns[colname].Hidden;
if (hidden && !_hiddenColumnNames.Contains(colname))
{
_hiddenColumnNames.Add(colname);
}
}
}
if (validcmblistcolumnsByColName.Count > 0)
{
int rowCount = 1;
foreach (var colKey in validcmblistcolumnsByColName.Keys)
{
StringBuilder validcmblist = validcmblistcolumnsByColName[colKey];
// ha kell validacios lista combobox oszlophoz
if (validcmblist.ToString().Contains("{0}"))
{
// csak eleg egyszer hozzaadni az osszes sorhoz
var refvalidstring = string.Format(validcmblist.ToString(), (excelrowIndex - 1).ToString());
validcmblist.Length = 0;
validcmblist.AppendFormat(refvalidstring);
}
// osszeallitom a validacios lista ertekeit
var cmbsource = datasource.Columns.First(a => a.Name == colKey).ComboDataSource;
if (cmbsource == null || cmbsource.Rows.Count == 0)
{
continue;
}
Dictionary<string, string> m_cmblista = null;
int ordercolindex = -1;
bool vanorder = false;
foreach (var col in cmbsource.Rows[0].Cells)
{
ordercolindex++;
if (col.Name == "Order")
{
vanorder = true;
break;
}
}
if (vanorder)
{
// Ez volt eredetileg
//m_cmblista = cmbsource.Rows.OrderBy(a => a.Cells[ordercolindex].Value)
// .ToDictionary(b => b.Cells.Where(c => c.Name == "Name").First().Value, a => a.ID.ToString());
m_cmblista = cmbsource.Rows.OrderBy(a => a.Cells[ordercolindex].Name)
.ToDictionary(b => b.Cells.Where(c => c.Name == "Name").First().Value, a => a.Cells.Where(d => d.Name == "Value").First().Value);
}
else
{
m_cmblista = cmbsource.Rows
.ToDictionary(b => b.Cells.Where(c => c.Name == "Name").First().Value, a => a.ID.ToString());
}
CreateDataValidationList(sheet, SharedstringPart, "X",
m_cmblista, validcmblist.ToString(), true, false, rowCount);
rowCount += m_cmblista.Count;
_hiddenColumnNames.Add("X");
_hiddenColumnNames.Add("Y");
}
}
if (validchklistcolumns.Length > 0)
{
// validacios lista checkboxos oszlophoz
if (validchklistcolumns.ToString().Contains("{0}"))
{
// csak eleg egyszer hozzaadni az osszes sorhoz
string refvalidstring = string.Format(validchklistcolumns.ToString(), (excelrowIndex - 1).ToString());
validchklistcolumns.Length = 0;
validchklistcolumns.AppendFormat(refvalidstring);
}
CreateDataValidationList(sheet, SharedstringPart, "Z",
new Dictionary<string, string>() { { StringResourcesUtil.GetString(133), "" },
{ StringResourcesUtil.GetString(134), "" } }, validchklistcolumns.ToString(), false, false, 1);
_hiddenColumnNames.Add("Z");
}
// oszlopok beallitasa (szelesseg)
foreach (int colindex in _ColumnMaxCharacterCount.Keys)
{
SetColumns(sheet, colindex, _ColumnMaxCharacterCount[colindex]);
}
// oszlopok elrejtese
// ha nem letezik hozza oszlopok tulajdonsag
Columns cols;
if (!sheet.Descendants<Columns>().Any())
{
cols = new Columns();
sheet.Append(cols);
}
else
{
cols = sheet.Descendants<Columns>().First();
}
foreach (string columnname in _hiddenColumnNames.OrderBy(a => a))
{
// oszlop letrehozasa, ahol elrejtjuk a validacios listat
uint colindex = GetColumnNameIndex(columnname);
Column col = new Column() { Min = new UInt32Value(colindex), Max = new UInt32Value(colindex), Hidden = true };
cols.Append(col);
}
sheet.Save();
refrowIndex += excelrowIndex - 1;
}
private string GetExtendedColumName(int colIndex)
{
colIndex++;
if (_ColumnName.Length >= colIndex)
{
return _ColumnName[colIndex - 1];
}
int elsobetu = (colIndex / _ColumnName.Length) - 1;
int masodikbetu = (colIndex % _ColumnName.Length) - 1;
return string.Format("{0}{1}", _ColumnName[elsobetu], _ColumnName[masodikbetu]);
}
/// <summary>
/// Felveszem az adatokat a cellakba.
///
/// Ez az új működés. Ez van használva a 2-nél több szintű exportra.
/// </summary>
/// <param name="rootNode"></param>
private void InsertMultipleLevelsDataIntoCells(Worksheet sheet, SharedStringTablePart SharedstringPart, ExcelDataSource datasource)
{
int excelrowIndex = 1;
int sumColCount = datasource.AllMultiLevelColumns.Select(a => a.Value.Count).Sum();
// checkbox validacios lista
StringBuilder validchklistcolumns = new StringBuilder(); // ebben azok a cellak vannak, amikre majd validacios listat akarunk allitani
// combobox validacios lista
Dictionary<string, StringBuilder> validcmblistcolumnsByColName = new Dictionary<string, StringBuilder>(); // ebben azok a cellak vannak, amikre majd validacios listat akarunk allitani
// elmentem elore az elrejteni kivant oszlopokat, mivel mindenkeppen csak sorrendben lehet hozzaadni a columns-k listahoz
List<string> _hiddenColumnNames = new List<string>();
#region fejlec
int excelcolIndex = 0;
int headersharedindex = 0;
foreach (var level in datasource.AllMultiLevelColumns.Keys)
{
string headertext = level + ". szint";
foreach (var column in datasource.AllMultiLevelColumns[level])
{
// cella referencia
string cellreference = GetExtendedColumName(excelcolIndex) + (excelrowIndex).ToString();
// uj cella (TD)
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
// szoveg objektum letrehozasa
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
headersharedindex = InsertSharedStringItem(headertext);
headertext = "";
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(headersharedindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, excelrowIndex, excelcolIndex, datasource.Rows.Count, sumColCount, false, false, false, true);
excelcolIndex++;
}
}
// header ID cella
// cella referencia
Cell newCellID = CreateSpreadsheetCellIfNotExist(sheet, IDColumnReference + (excelrowIndex).ToString());
int IDindex = InsertSharedStringItem("");
// majd index alapjan referenciat adok ra
newCellID.CellValue = new CellValue(IDindex.ToString());
// ez bizony egy sharedstring tipus
newCellID.DataType = new EnumValue<CellValues>(CellValues.SharedString);
newCellID.StyleIndex = (UInt32Value)1U;
excelrowIndex++;
excelcolIndex = 0;
foreach (var level in datasource.AllMultiLevelColumns.Keys)
{
for (int sourcecolIndex = 0; sourcecolIndex < datasource.AllMultiLevelColumns[level].Count; sourcecolIndex++)
{
var datasourceCol = datasource.AllMultiLevelColumns[level][sourcecolIndex];
// cella referencia
string cellreference = GetExtendedColumName(excelcolIndex) + (excelrowIndex).ToString();
// uj cella (TD)
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
// szoveg objektum letrehozasa
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
headersharedindex = InsertSharedStringItem(datasourceCol.Value);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(headersharedindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, excelrowIndex, excelcolIndex, datasource.Rows.Count, sumColCount, false, false, false, true);
// maximalis karakter szamolas
if (!_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
|| (_ColumnMaxCharacterCount.Keys.Contains(excelcolIndex + 1)
&& _ColumnMaxCharacterCount[excelcolIndex + 1] < datasourceCol.Value.Length))
{
_ColumnMaxCharacterCount[excelcolIndex + 1] = datasourceCol.Value.Length;
}
excelcolIndex++;
}
}
// header ID cella
// cella referencia
newCellID = CreateSpreadsheetCellIfNotExist(sheet, IDColumnReference + (excelrowIndex).ToString());
IDindex = InsertSharedStringItem("");
// majd index alapjan referenciat adok ra
newCellID.CellValue = new CellValue(IDindex.ToString());
// ez bizony egy sharedstring tipus
newCellID.DataType = new EnumValue<CellValues>(CellValues.SharedString);
newCellID.StyleIndex = (UInt32Value)1U;
#endregion
excelrowIndex++;
// sorok felvetele
foreach (var excelRow in datasource.Rows)
{
// uj sor (TR)
#region Cellak
excelcolIndex = 0;
foreach (var cell in excelRow.Cells.OrderBy(r => r.LevelIndex))
{
InsertNewCell(sheet, datasource, cell, excelrowIndex, excelcolIndex, ref validcmblistcolumnsByColName, ref validchklistcolumns);
excelcolIndex++;
}
//if (UserExcelCells != null)
//{
// if (UserExcelCells.Keys.First()[0] > IDColumnReference[0])
// {
// // ha a felhasznalo altal kert plusz mezok kesobbiek, mint a kert ID mezo, akkor eloszor az IDkat vesszuk fel
// // ID elmentese
// InsertIDColumns(excelRow, sheet, SharedstringPart, _hiddenColumnNames, excelrowIndex, 0);
// // utana johet a kert mezok
// InsertUserCellsValues(sheet, SharedstringPart, excelrowIndex);
// }
// else
// {
// // ha a felhasznalo altal kert plusz mezok elobbiek, mint a kert ID mezo, akkor eloszor a kert mezoket vesszuk fel
// InsertUserCellsValues(sheet, SharedstringPart, excelrowIndex);
// // utana johet az ID elmentese
// InsertIDColumns(excelRow, sheet, SharedstringPart, _hiddenColumnNames, excelrowIndex, 0);
// }
//}
//else
//{
// // ha nincs kert mezo, akkor siman az ID mentese jon
// InsertIDColumns(excelRow, sheet, SharedstringPart, _hiddenColumnNames, excelrowIndex, 0);
//}
excelrowIndex++;
}
#endregion
//if (UserExcelColumns != null)
//{
// // ha el kell egy oszlopot tuntetni, akkor felveszem azok koze
// foreach (var colname in this.UserExcelColumns.Keys)
// {
// bool hidden = UserExcelColumns[colname].Hidden;
// if (hidden && !_hiddenColumnNames.Contains(colname))
// _hiddenColumnNames.Add(colname);
// }
//}
//if (validcmblistcolumnsByColName.Count > 0)
//{
// foreach (var colKey in validcmblistcolumnsByColName.Keys)
// {
// StringBuilder validcmblist = validcmblistcolumnsByColName[colKey];
// // ha kell validacios lista combobox oszlophoz
// if (validcmblist.ToString().Contains("{0}"))
// {
// // csak eleg egyszer hozzaadni az osszes sorhoz
// string refvalidstring = string.Format(validcmblist.ToString(), (excelrowIndex - 1).ToString());
// validcmblist.Length = 0;
// validcmblist.AppendFormat(refvalidstring);
// }
// // osszeallitom a validacios lista ertekeit
// var cmbsource = datasource.Columns.Where(a => a.Name == colKey).First().ComboDataSource;
// if (cmbsource == null || cmbsource.Rows.Count == 0)
// continue;
// Dictionary<string, string> m_cmblista = null;
// int ordercolindex = -1;
// bool vanorder = false;
// foreach (var col in cmbsource.Rows.First().Cells)
// {
// ordercolindex++;
// if (col.Name == "Order")
// {
// vanorder = true;
// break;
// }
// }
// if (vanorder)
// {
// m_cmblista = cmbsource.Rows.OrderBy(a => a.Cells[ordercolindex].Value)
// .ToDictionary(b => b.Cells.Where(c => c.Name == "Name").First().Value, a => a.ID.ToString());
// }
// else
// {
// m_cmblista = cmbsource.Rows
// .ToDictionary(b => b.Cells.Where(c => c.Name == "Name").First().Value, a => a.ID.ToString());
// }
// CreateDataValidationList(sheet, SharedstringPart, "XX",
// m_cmblista, validcmblist.ToString(), true, true);
// _hiddenColumnNames.Add("XX");
// _hiddenColumnNames.Add("YY");
// }
//}
//if (validchklistcolumns.Length > 0)
//{
// // validacios lista checkboxos oszlophoz
// if (validchklistcolumns.ToString().Contains("{0}"))
// {
// // csak eleg egyszer hozzaadni az osszes sorhoz
// string refvalidstring = string.Format(validchklistcolumns.ToString(), (excelrowIndex - 1).ToString());
// validchklistcolumns.Length = 0;
// validchklistcolumns.AppendFormat(refvalidstring);
// }
// CreateDataValidationList(sheet, SharedstringPart, "ZZ",
// new Dictionary<string, string>() { { LanguageString.GetString(LanguageStringTypes.Igen), "" },
// { LanguageString.GetString(LanguageStringTypes.Nem), "" } }, validchklistcolumns.ToString(), false,true);
// _hiddenColumnNames.Add("ZZ");
//}
// oszlopok beallitasa (szelesseg)
foreach (int colindex in _ColumnMaxCharacterCount.Keys)
{
SetColumns(sheet, colindex, _ColumnMaxCharacterCount[colindex]);
}
// oszlopok elrejtese
// ha nem letezik hozza oszlopok tulajdonsag
Columns cols;
if (!sheet.Descendants<Columns>().Any())
{
cols = new Columns();
sheet.Append(cols);
}
else
{
cols = sheet.Descendants<Columns>().First();
}
//foreach (string columnname in _hiddenColumnNames.OrderBy(a => a))
//{
// // oszlop letrehozasa, ahol elrejtjuk a validacios listat
// uint colindex = GetColumnNameIndex(columnname);
// Column col = new Column() { Min = new UInt32Value(colindex), Max = new UInt32Value(colindex), Hidden = true };
// cols.Append(col);
//}
sheet.Save();
}
#endregion
private void InsertNewCell(Worksheet sheet, ExcelDataSource datasource, ExcelDataSource.Column cell, int rowIndex, int colIndex, ref Dictionary<string, StringBuilder> validcmblistcolumnsByColName, ref StringBuilder validchklistcolumns)
{
#region Cella felvetele
if (GetExtendedColumName(colIndex) == IDColumnReference)
{
return;
}
int sharedindex = 0;
// cella referencia
string cellreference = GetExtendedColumName(colIndex) + (rowIndex).ToString();
// uj cella (TD)
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
string cellText = cell.Value;
var datatype = datasource.AllMultiLevelColumns[cell.LevelIndex].Where(a => a.Name == cell.Name).Select(a => a.Type).First();
switch (datatype)
{
case ExcelDataSource.ColumnType.String:
// szoveg
// szoveg objektum letrehozasa
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
sharedindex = InsertSharedStringItem(cellText);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(sharedindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, rowIndex, colIndex, datasource.Rows.Count, datasource.Columns.Count, false, false, false);
// maximalis karakter szamolas
if (!_ColumnMaxCharacterCount.Keys.Contains(colIndex + 1)
|| (_ColumnMaxCharacterCount.Keys.Contains(colIndex + 1)
&& _ColumnMaxCharacterCount[colIndex + 1] < cellText.Length))
{
_ColumnMaxCharacterCount[colIndex + 1] = cellText.Length;
}
break;
case ExcelDataSource.ColumnType.Combo:
sharedindex = InsertSharedStringItem(cellText);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(sharedindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, rowIndex, colIndex, datasource.Rows.Count, datasource.Columns.Count, false, false, false);
// maximalis karakter szamolas
if (!_ColumnMaxCharacterCount.Keys.Contains(colIndex + 1)
|| (_ColumnMaxCharacterCount.Keys.Contains(colIndex + 1)
&& _ColumnMaxCharacterCount[colIndex + 1] < cellText.Length))
{
_ColumnMaxCharacterCount[colIndex + 1] = cellText.Length;
}
// ha combobox tipusu
// akkor megjegyzem a cellat es kesobb rahuzok egy validacios listat
if (cell.ComboDataSource.Rows.Count > 0)
{
// csak akkor vegyek fel validacios listat, ha vannak hozza ertekek
if (!validcmblistcolumnsByColName.ContainsKey(cell.Name))
{
// ha még nincs, akkor létrehozom
validcmblistcolumnsByColName.Add(cell.Name, new StringBuilder());
}
if (rowIndex == 3)
{
// validációs lista készítése
validcmblistcolumnsByColName[cell.Name].AppendFormat("{0}2:{0}",
GetExtendedColumName(colIndex)).Append("{0} ");
}
// beallitom a cella stilusat
SetStyleIndex(newCell, rowIndex, colIndex, datasource.Rows.Count, datasource.Columns.Count, false, false, KellVedelem);
}
break;
case ExcelDataSource.ColumnType.Checkbox:
// checkbox
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// beallitom a cella stilusat
SetStyleIndex(newCell, rowIndex, colIndex, datasource.Rows.Count, datasource.Columns.Count, false, false, KellVedelem);
// eloszor letrehozom a ShareStringTable-ben vagy megkeresem van-e mar
sharedindex = 0;
if (string.IsNullOrWhiteSpace(cellText))
{
sharedindex = InsertSharedStringItem(StringResourcesUtil.GetString(134/*Nem*/));
}
else
{
bool ertek = false;
bool isvalid = bool.TryParse(cellText, out ertek);
if (isvalid == false)
{
ertek = cellText.Trim() == "1";
}
if (ertek)
{
sharedindex = InsertSharedStringItem(StringResourcesUtil.GetString(133)/*Igen*/);
}
else
{
sharedindex = InsertSharedStringItem(StringResourcesUtil.GetString(134)/*Nem*/);
}
}
newCell.CellValue = new CellValue(sharedindex.ToString());
if (rowIndex == 3)
{
// validációs lista készítése
validchklistcolumns.AppendFormat("{0}2:{0}",
GetExtendedColumName(colIndex)).Append("{0} ");
}
break;
}
#endregion
}
private void InsertUserCellsValues(Worksheet sheet, SharedStringTablePart SharedstringPart, int rowIndex)
{
// a felhasznalo altal kert cellak beirasa
var cells = (from x in UserExcelCells.Keys
where x.EndsWith(rowIndex.ToString())
select x).OrderBy(a => a);
foreach (var cellreference in cells)
{
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
int IDindex = InsertSharedStringItem(UserExcelCells[cellreference]);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(IDindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
}
}
private void InsertIDColumns(ExcelDataSource.Row datasourceRow, Worksheet sheet, SharedStringTablePart SharedstringPart, List<string> _hiddenColumnNames, int rowIndex, int refrowIndex)
{
// ID elmentese
string rowID = datasourceRow.ID.ToString();
Cell newCell = CreateSpreadsheetCellIfNotExist(sheet, IDColumnReference + (refrowIndex + rowIndex).ToString());
int IDindex = InsertSharedStringItem(rowID);
// majd index alapjan referenciat adok ra
newCell.CellValue = new CellValue(IDindex.ToString());
// ez bizony egy sharedstring tipus
newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
newCell.StyleIndex = (UInt32Value)1U;
if (!_hiddenColumnNames.Contains(IDColumnReference))
{
_hiddenColumnNames.Add(IDColumnReference);
}
}
#region Design
private void SetStyleIndex(Cell cell, int rowIndex, int colIndex, int maxrowIndex, int maxcolIndex, bool hasSubrow, bool isSubrow, bool isModified, bool header = false)
{
if (!isModified)
{ // nem modosithato cellak
if (rowIndex == 1 || header)
{
// header
cell.StyleIndex = (UInt32Value)1U;
//if (colIndex == 1 && isSubrow) // 2.szintu es elso oszlop
// cell.StyleIndex = (UInt32Value)0U;
}
else if (!isSubrow)
{
if (!hasGridSubrow)
{
cell.StyleIndex = (UInt32Value)5U;
}
else if (!hasSubrow)
{
// 1. szint, nincs altetele
// kozbenso
cell.StyleIndex = (UInt32Value)4U;
}
else
{
// 1.szint sor, van altetele
// kozbenso
cell.StyleIndex = (UInt32Value)2U;
}
}
else
{
// 2.szint sor
if (rowIndex < maxrowIndex)
{
if (colIndex == 1)
{
cell.StyleIndex = (UInt32Value)0U; // elso oszlop
}
else
{
// kozbenso
cell.StyleIndex = (UInt32Value)5U;
}
}
else
{
// utolso sor
//if (colIndex == 1)
// cell.StyleIndex = (UInt32Value)6U;
//else // kozbenso
cell.StyleIndex = (UInt32Value)3U;
}
}
}
else
{ // modosithato cellak
if (rowIndex == 1 || header)
{
// header
cell.StyleIndex = (UInt32Value)8U;
if (colIndex == 1 && isSubrow) // 2.szintu es elso oszlop
{
cell.StyleIndex = (UInt32Value)7U;
}
}
else if (!isSubrow)
{
if (!hasGridSubrow)
{
cell.StyleIndex = (UInt32Value)12U;
}
else if (!hasSubrow)
{
// 1. szint, nincs altetele
// kozbenso
cell.StyleIndex = (UInt32Value)11U;
}
else
{
// 1.szint sor, van altetele
// kozbenso
cell.StyleIndex = (UInt32Value)9U;
}
}
else
{
// 2.szint sor
if (rowIndex < maxrowIndex)
{
if (colIndex == 1)
{
cell.StyleIndex = (UInt32Value)7U; // elso oszlop
}
else
{
// kozbenso
cell.StyleIndex = (UInt32Value)12U;
}
}
else
{
// utolso sor
cell.StyleIndex = colIndex == 1 ? (UInt32Value)13U : (UInt32Value)10U;
}
}
}
}
#endregion
/// <summary>
/// Letrehoz egy validacios listat az atadott lista alapjan.
/// </summary>
/// <param name="sheet">Aktiv sheet.</param>
/// <param name="sharedstrintable">Aktiv sharedstringtablepart</param>
/// <param name="containscolumnname">A validacios listat tartalmazo oszlop neve</param>
/// <param name="lista">Maga a lista elemei tomb</param>
/// <param name="referencelist">Azon cellak neve, amelyekre ra lesz huzva a lista. pl: C2:C4</param>
private void CreateDataValidationList(Worksheet sheet, SharedStringTablePart sharedstrintable, string containscolumnname, Dictionary<string, string> lista, string referencelist, bool iscombotype, bool multilevel, int fromRow)
{
int rowIndex = fromRow;
// lista inicializalasa
string validationformula = string.Format("${0}${2}:${0}${1}", containscolumnname, (fromRow + lista.Count - 1).ToString(), fromRow.ToString());
foreach (var item in lista.Keys)
{
// ertekek mentese
string cellreference = containscolumnname + rowIndex.ToString();
Cell cell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
int sharedstringindex = InsertSharedStringItem(item);
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.CellValue = new CellValue(sharedstringindex.ToString());
rowIndex++;
}
if (iscombotype)
{
rowIndex = 1;
foreach (var item in lista.Values)
{
// ertekek mentese
string cellreference = multilevel ? "YY" + rowIndex.ToString() : "Y" + rowIndex.ToString();
Cell cell = CreateSpreadsheetCellIfNotExist(sheet, cellreference);
int sharedstringindex = InsertSharedStringItem(item);
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.CellValue = new CellValue(sharedstringindex.ToString());
rowIndex++;
}
}
sheet.Save();
// validacios lista hozzarendelese
// ha nem letezik hozza validacios lista tulajdonsag
DataValidations validlists;
if (!sheet.Descendants<DataValidations>().Any())
{
validlists = new DataValidations();
sheet.Append(validlists);
}
else
{
validlists = sheet.Descendants<DataValidations>().First();
}
// leellenorzom, hogy van-e mar felveve egyaltalan erre a listaelemekre validacios lista
var datavalidationlista = validlists.Descendants<DataValidation>().Where(a => a.Formula1.Text == validationformula);
bool vanmarilyenlista = datavalidationlista.Any();
if (vanmarilyenlista)
{
// ha van mar ilyen lista, akkor csak a formulahoz adom hozza a cellakat
DataValidation validlist = datavalidationlista.First();
validlist.SequenceOfReferences.InnerText += " " + referencelist.Trim();
}
else
{
// ha meg nincs ilyen lista, felveszek egy ujat
// lista felvetele
DataValidation validlist = new DataValidation(
new Formula1(validationformula))
{
AllowBlank = true,
Type = DataValidationValues.List,
SequenceOfReferences = new ListValue<StringValue>() { InnerText = referencelist.Trim() },
ShowErrorMessage = true,
ShowInputMessage = true
};
validlists.Append(validlist);
}
}
private 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"};
public static uint GetColumnNameIndex(string colname)
{
uint index = 1;
foreach (var cname in _ColumnName)
{
if (cname.Equals(colname))
{
break;
}
index++;
}
return index;
}
#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.
private Cell CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName)
{
string columnName = GetColumnName(cellName);
uint rowIndex = GetRowIndex(cellName);
Cell cell = new Cell();
//var row = worksheet.Descendants<Row>().FirstOrDefault(a=> a.RowIndex == rowIndex);
Row row = null;
_ = _cellrows.TryGetValue(rowIndex, out row);
// 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 (row == null)
{
row = new Row();
row.RowIndex = new UInt32Value(rowIndex);
cell = new Cell() { CellReference = new StringValue(cellName) };
row.Append(cell);
_cellrows.Add(rowIndex, row);
//worksheet.Descendants<SheetData>().First().Append(row);
}
else
{
var cells = row.Elements<Cell>().FirstOrDefault(c => c.CellReference.Value == cellName);
// If the row does not contain the specified cell, create the specified cell.
if (cells == null)
{
cell = new Cell() { CellReference = new StringValue(cellName) };
row.Append(cell);
}
}
return cell;
}
#endregion
#region SaveExcelRows
private void SaveExcelRows(Worksheet worksheet)
{
var sheetData = worksheet.Descendants<SheetData>().First();
sheetData.Append(_cellrows.Values);
}
#endregion
#region InsertSharedStringItem
int _maxstringtableindex = 0;
// 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.
private int InsertSharedStringItem(string text)
{
int i = 0;
if (!_sharedstringtable.TryGetValue(text, out i))
{
//var maxindex = _sharedstringtable.Count > 0 ? _sharedstringtable.Max(a => a.Value) : -1;
i = _sharedstringtable[text] = _maxstringtableindex++;
}
return i;
}
#endregion
#region SaveSharedStringTable
/// <summary>
/// A memóriából mentek excelbe.
/// </summary>
/// <param name="shareStringPart"></param>
private void SaveSharedStringTable(SharedStringTablePart shareStringPart)
{
// If the part does not contain a SharedStringTable, create one.
if (shareStringPart.SharedStringTable == null)
{
shareStringPart.SharedStringTable = new SharedStringTable();
}
foreach (var item in _sharedstringtable)
{
// 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(item.Key)));
}
shareStringPart.SharedStringTable.Save();
}
#endregion
#region GetColumnName
// Given a cell name, parses the specified cell to get the column name.
private 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.
private 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
/// <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 || string.IsNullOrWhiteSpace(columnName))
{
return null;
}
IEnumerable<Cell> cells = row.Elements<Cell>().Where(c => string.Compare
(c.CellReference.Value, columnName +
rowIndex, true) == 0);
return !cells.Any() ? null : cells.First();
}
/// <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);
return !myRows.Any() ? null : myRows.First();
}
/// <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 == null || cell.CellValue == null)
{
return "";
}
// számjegy
if (cell.DataType == null || cell.ChildElements.Count > 1 || cell.DataType == "n")
{
return cell.CellValue.InnerText.Trim();
}
// string
if (int.TryParse(cell.CellValue.Text, out index))
{
return table.Elements<SharedStringItem>().ElementAt(index).InnerText.Trim();
}
return "";
}
public static bool GetDateTimeCellValue(SharedStringTable table, Cell cell, out DateTime value)
{
int dateInt = -1;
if (cell == null || cell.CellValue == null)
{
value = new DateTime();
return false;
}
if (int.TryParse(cell.CellValue.Text, out dateInt) && cell.DataType == null)
{
value = DateTime.FromOADate(dateInt);
return true;
}
if (cell.DataType.Value == CellValues.SharedString && int.TryParse(cell.CellValue.Text, out dateInt))
{
return DateTime.TryParse(table.Elements<SharedStringItem>().ElementAt(dateInt).InnerText, out value);
}
value = new DateTime();
return false;
}
public static bool GetIntCellValue(SharedStringTable table, Cell cell, out int value)
{
int dateInt = -1;
if (cell == null || cell.CellValue == null)
{
value = new int();
return false;
}
if (int.TryParse(cell.CellValue.Text, out dateInt) && cell.DataType == null)
{
value = dateInt;
return true;
}
if (cell.DataType.Value == CellValues.SharedString && int.TryParse(cell.CellValue.Text, out dateInt))
{
return int.TryParse(table.Elements<SharedStringItem>().ElementAt(dateInt).InnerText, out value);
}
value = new int();
return false;
}
public static bool GetDoubleCellValue(SharedStringTable table, Cell cell, out double value)
{
int dateInt = -1;
if (cell == null || cell.CellValue == null)
{
value = new double();
return false;
}
if (int.TryParse(cell.CellValue.Text, out dateInt) && cell.DataType == null)
{
value = dateInt;
return true;
}
if (cell.DataType.Value == CellValues.SharedString && int.TryParse(cell.CellValue.Text, out dateInt))
{
return double.TryParse(table.Elements<SharedStringItem>().ElementAt(dateInt).InnerText, out value);
}
value = new double();
return false;
}
#endregion
#region Events
public delegate void OnBeginExcelExportHandler(object sender, OnBeginExcelExportHandlerEventArgs e);
public event OnBeginExcelExportHandler OnBeginExcelExportCommand;
public class OnBeginExcelExportHandlerEventArgs
{
public bool KellMasodikSzint = true;
/// <summary>
/// Itt lehet definialni, hogy az export soran milyen az egyes sorokban levo cellakban
/// milyen plusz ertek legyen felveve.
/// </summary>
public Dictionary<string, string> ExcelCells = new Dictionary<string, string>();
/// <summary>
/// Itt lehet az oszlopoknal definialni, hogy melyik oszlopok ne latszodjanak.
/// </summary>
public Dictionary<string, ExcelColumn> ExcelColumns = new Dictionary<string, ExcelColumn>();
public string IDColumnReference = "V";
public bool KellVedelem = false;
// Zsolt
public Dictionary<string, Dictionary<string, string>> KepletesOszlopok = new Dictionary<string, Dictionary<string, string>>();
/// <summary>
/// Itt lehet új oszlopot a táblázathoz hozzáadni, amiben képlet van
/// Ha az oszlop neve kívül esik a tartományon, akkor az utolsó helyre rakja, egyébként beszúrja a megfelelő helyre
/// A képletben a sorváltozót {0} formával kell megadni pl.: =A{0}
/// </summary>
/// <param name="Oszlop">Oszlop neve (A, B, C, ...), ha üres string, akkor ez lesz az utolsó oszlop</param>
/// <param name="OszlopFejlec">Új oszlop fejléce</param>
/// <param name="Keplet">Formula, FONTOS!!! ANGOLUL KELL A KEPLETET MEGADNI</param>
public void KepletesOszlopHozzaadasa(string Oszlop, string OszlopFejlec, string Keplet)
{
Dictionary<string, string> OszlopKeplet = new Dictionary<string, string>();
OszlopKeplet.Add(Oszlop, Keplet);
Dictionary<string, Dictionary<string, string>> KepletesOszlopok = new Dictionary<string, Dictionary<string, string>>();
this.KepletesOszlopok.Add(OszlopFejlec, OszlopKeplet);
}
}
private bool KellMasodikSzint = true;
private Dictionary<string, string> UserExcelCells = null;
private Dictionary<string, ExcelColumn> UserExcelColumns = null;
// Zsolt
private Dictionary<string, Dictionary<string, string>> KepletesOszlopok = null;
public class ExcelColumn
{
public bool Hidden = true;
}
private void BeginExcelExportCall(object sender, OnBeginExcelExportHandlerEventArgs e)
{
if (OnBeginExcelExportCommand != null)
{
OnBeginExcelExportCommand?.Invoke(this, e);
this.UserExcelCells = e.ExcelCells;
this.UserExcelColumns = e.ExcelColumns;
this.KellMasodikSzint = e.KellMasodikSzint;
this.IDColumnReference = e.IDColumnReference;
this.KellVedelem = e.KellVedelem;
this.KepletesOszlopok = e.KepletesOszlopok;
}
}
public delegate void OnExcelInitRowHandler(object sender, OnExcelInitRowHandlerEventArgs e);
public event OnExcelInitRowHandler OnExcelInitRowCommand;
public class OnExcelInitRowHandlerEventArgs
{
}
private void ExcelInitRowCall(object sender, OnExcelInitRowHandlerEventArgs e)
{
OnExcelInitRowCommand?.Invoke(this, e);
}
#endregion
#region Properties
string _idcolref = "V";
public string IDColumnReference
{
get { return _idcolref; }
set { _idcolref = value; }
}
public bool KellVedelem { get; set; }
#endregion
}
}