Export list to excel using asp.net core set header style - asp.net-core

I'm exporting data to excel. I would like to add excel header color and header width. I tried different way but not working. Please see my below function. I'm using asp.net and OpenXml library. Any one expert here to suggest any solution. Thanks
public byte[] ExportExcelFile<T>(List<T> data, string sheetName)
{
var table = ToDataTable(data);
var memoryStream = new MemoryStream();
using (var workbook = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook))
{
workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new Workbook();
workbook.WorkbookPart.Workbook.Sheets = new Sheets();
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
sheetPart.Worksheet = new Worksheet(sheetData);
var sheets = workbook.WorkbookPart.Workbook.GetFirstChild<Sheets>();
var relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
sheets.Append(new Sheet { Id = relationshipId, SheetId = 1, Name = sheetName });
var headerRow = new Row();
var columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
var newRow = new Row();
foreach (var col in columns)
{
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbook.Save();
workbook.Close();
}
return memoryStream.ToArray();
}

You could refer the following steps to add css style for the excel content:
Add Stylesheet. Create a GenerateStylesheet class and contain the following code:
private Stylesheet GenerateStylesheet()
{
Stylesheet styleSheet = null;
//Fonts can have one or more Font children which each have different properties like FontSize, Bold, Color, and etc.
//Here, we add two Font children to the Fonts object. The first one is the default font use by all cells, and the second one is specific to header.
Fonts fonts = new Fonts(
new Font( // Index 0 - default
new FontSize() { Val = 10 }
),
new Font( // Index 1 - header
new FontSize() { Val = 10 },
new Bold(),
new Color() { Rgb = "FFFFFF" }
));
//Fills can have one or more Fill children which you can set its ForegroundColor.
Fills fills = new Fills(
new Fill(new PatternFill() { PatternType = PatternValues.None }), // Index 0 - default
new Fill(new PatternFill() { PatternType = PatternValues.Gray125 }), // Index 1 - default
new Fill(new PatternFill(new ForegroundColor { Rgb = new HexBinaryValue() { Value = "66666666" } })
{ PatternType = PatternValues.Solid }) // Index 2 - header
);
//Borders can have one or more Border children which each defines how the border should look like
Borders borders = new Borders(
new Border(), // index 0 default
new Border( // index 1 black 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())
);
//CellFormats which has one or many CellFormat children. Each CellFormat gets the index of Font, Border, Fill, or etc.
CellFormats cellFormats = new CellFormats(
new CellFormat(), // default
new CellFormat { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = true }, // body
new CellFormat { FontId = 1, FillId = 2, BorderId = 1, ApplyFill = true } // header
);
styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);
return styleSheet;
}
Add the style to the workbook.
Add a WorkbookStylePart to the WorkbookPart and initialize its Stylesheet:
//Add a WorkbookStylePart to the WorkbookPart and initialize its Stylesheet:
WorkbookStylesPart stylePart = workbook.WorkbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();
Add style to Cells
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
cell.StyleIndex = 2; //add css style to Cells
headerRow.AppendChild(cell);
}
The Complete ExportExcelFile code:
public byte[] ExportExcelFile<T>(List<T> data, string sheetName)
{
var table = ToDataTable(data);
var memoryStream = new MemoryStream();
using (var workbook = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook))
{
workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new Workbook();
workbook.WorkbookPart.Workbook.Sheets = new Sheets();
//Add a WorkbookStylePart to the WorkbookPart and initialize its Stylesheet:
WorkbookStylesPart stylePart = workbook.WorkbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
sheetPart.Worksheet = new Worksheet(sheetData);
var sheets = workbook.WorkbookPart.Workbook.GetFirstChild<Sheets>();
var relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
sheets.Append(new Sheet { Id = relationshipId, SheetId = 1, Name = sheetName });
var headerRow = new Row();
var columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
cell.StyleIndex = 2; //add css style to Cells
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
var newRow = new Row();
foreach (var col in columns)
{
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dsrow[col].ToString()); //
cell.StyleIndex = 1; //add css style to Cells
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbook.Save();
workbook.Close();
}
return memoryStream.ToArray();
}
Then, when export excel using the above code:
public IActionResult Privacy()
{
List<Employee> Students = new List<Employee>(){
new Employee() { Name = "Pradeep", salary = 15000, EmpId = 100 },
new Employee() { Name = "Smith", salary = 25000, EmpId = 101},
new Employee() { Name = "John", salary = 21000, EmpId = 102 }
};
byte[] result = ExportExcelFile<Employee>(Students, "sheetA");
return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
//return View();
}
The result as below:
Update:
To set the columns width, you could update the ExportExcelFile method as below:
public byte[] ExportExcelFile<T>(List<T> data, string sheetName)
{
var table = ToDataTable(data);
var memoryStream = new MemoryStream();
using (var workbook = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = workbook.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
// Adding style
WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();
// Setting up columns
Columns widthcolumns = new Columns(
new Column // first column
{
Min = 1,
Max = 1,
Width = 20,
CustomWidth = true
},
new Column // second columns
{
Min = 2,
Max = 3,
Width = 15,
CustomWidth = true
},
new Column // third column
{
Min = 4,
Max = 4,
Width = 8,
CustomWidth = true
});
worksheetPart.Worksheet.AppendChild(widthcolumns);
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = sheetName };
sheets.Append(sheet);
workbookPart.Workbook.Save();
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
var headerRow = new Row();
var columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
cell.StyleIndex = 2; //add css style to Cells
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
var newRow = new Row();
foreach (var col in columns)
{
var cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dsrow[col].ToString()); //
cell.StyleIndex = 1; //add css style to Cells
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbook.Save();
workbook.Close();
}
return memoryStream.ToArray();
}
The result as below:

Related

Create multiple frames in code behind in Xamarin.Forms

I want to create multiple frames in code-behind, but when creating frames in loop and adding elements in content, only one frame has all elements and other frames are empty! why?
My code is:
private void searchResults_ItemTapped(object sender, ItemTappedEventArgs e)
{
searchResults.IsVisible = false;
Indexes Indexes = (Indexes)searchResults.SelectedItem;
_viewModel.Items.Add(db.RequestToJson(Indexes.Index));
searchbar.Text = string.Empty;
StackLayout Words = new StackLayout();
StackLayout WordDetail = new StackLayout();
foreach (var dt in _viewModel.Items)
{
AddTextToLabel(nameof(dt.Word), dt.Word, WordDetail);
var BaseLang = dt.BaseLang;
AddTextToLabel(nameof(BaseLang.Meaning), BaseLang.Meaning, WordDetail);
Words.Children.Add(new Frame { BackgroundColor = Color.FromHex("2196F3"), Padding = 5, HasShadow = false, Margin = new Thickness(10, 10, 80, 10), Content = new StackLayout { Children = { WordDetail } } });
}
SearchResult.Content = Words;
SearchResult.IsVisible = true;
}
private void AddTextToLabel(string title, string data, StackLayout worddetail)
{
worddetail.Children.Add(new Label { Text = title + ":", FontAttributes = FontAttributes.Bold, TextColor = Color.White });
worddetail.Children.Add(new Label { Text = data, TextColor = Color.White });
}
And here is the result:
you are using the same instance of WordDetail in every iteration of the loop
instead, create a new instance each time
foreach (var dt in _viewModel.Items)
{
StackLayout WordDetail = new StackLayout();
I reproduced your situation locally by copying your code. I solved it by moving the WordDetail declaration inside the foreach like so:
StackLayout Words = new StackLayout();
foreach (var dt in _viewModel.Items)
{
StackLayout WordDetail = new StackLayout();
AddTextToLabel(nameof(dt.Word), dt.Word, WordDetail);
var BaseLang = dt.BaseLang;
AddTextToLabel(nameof(BaseLang.Meaning), BaseLang.Meaning, WordDetail);
Words.Children.Add(new Frame { BackgroundColor = Color.FromHex("2196F3"), Padding = 5, HasShadow = false, Margin = new Thickness(10, 10, 80, 10), Content = new StackLayout { Children = { WordDetail } } });
}

EPPlus two color conditional date format

I have a column with dates and I want to conditionally color any cell that is older that 2 week yellow, and any that is older than 90 days red. I can't figure out how to do that.
Should be able to just add the conditions like any other. You can use the TODAY() function in excel and subtract:
[TestMethod]
public void Conditional_Formatting_Date()
{
//https://stackoverflow.com/questions/56741642/epplus-two-color-conditional-date-format
var file = new FileInfo(#"c:\temp\Conditional_Formatting_Date.xlsx");
if (file.Exists)
file.Delete();
//Throw in some data
var dataTable = new DataTable("tblData");
dataTable.Columns.AddRange(new[] {
new DataColumn("Col1", typeof(DateTime)),
new DataColumn("Col3", typeof(string))
});
var rnd = new Random();
for (var i = 0; i < 100; i++)
{
var row = dataTable.NewRow();
row[0] = DateTime.Now.AddDays(-rnd.Next(1, 100));
row[1] = $"=TODAY() - A{i +1}";
dataTable.Rows.Add(row);
}
//Create a test file
using (var package = new ExcelPackage(file))
{
//Make the stylesheet
var ws = package.Workbook.Worksheets.Add("table");
var range = ws.Cells[1, 1].LoadFromDataTable(dataTable, false);
ws.Column(1).Style.Numberformat.Format = "mm-dd-yy";
ws.Column(1).AutoFit();
//Add the calc check
var count = 0;
foreach (DataRow row in dataTable.Rows)
ws.Cells[++count, 2].Formula = row[1].ToString();
//Add the conditions - order matters
var rangeA = range.Offset(0, 0, count, 1);
var condition90 = ws.ConditionalFormatting.AddExpression(rangeA);
condition90.Style.Font.Color.Color = Color.White;
condition90.Style.Fill.PatternType = ExcelFillStyle.Solid;
condition90.Style.Fill.BackgroundColor.Color = Color.Red;
condition90.Formula = "TODAY() - A1> 90";
condition90.StopIfTrue = true;
var condition14 = ws.ConditionalFormatting.AddExpression(rangeA);
condition14.Style.Font.Color.Color = Color.Black;
condition14.Style.Fill.PatternType = ExcelFillStyle.Solid;
condition14.Style.Fill.BackgroundColor.Color = Color.Yellow;
condition14.Formula = "TODAY() - A1> 14";
package.Save();
}
}
Which gives this in the output:
I am assuming that you have the column number of the date column and number of rows in your records. Also, the following loop is under assumption that the first row is your column header and records begin from second row. Change the loop counter's initialization and assignment accordingly.
int rowsCount; //get your no of rows
int dateColNumber; //Assign column number in excel file of your date column
string cellValue;
DateTime dateValue;
DateTime today = DateTime.Now;
double daysCount;
for(int i=1;i<rowsCount;i++)
{
cellValue = ws.Cells[i + 1, dateColNumber].Text.ToString(); //First row is header start from second
if(DateTime.TryParse(cellValue,out dateValue))
{
daysCount = (today - dateValue).Days;
if(daysCount>90)
{
ws.Cells[i + 1,dateColNumber].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
ws.Cells[i + 1,dateColNumber].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Red);
}
else if(daysCount>14)
{
ws.Cells[i + 1, dateColNumber].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
ws.Cells[i + 1, dateColNumber].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Yellow);
}
}
}

Colouring Excel cell with condition using DocumentFormat.OpenXml

I would like to know if someone have worked on DocumentFormat.OpenXml as I have an issue with the colouring of sheet cell on condition using DocumentFormat.Spreadsheet.
Now I can create the colour for the 1st time but I need to open the same excel sheet and based on the condition I need to colour a particular cell. E.g. if cell D1 is yellow then D2 may be green or yellow.
e.g.
Name IpAddress Region Details
Switch 10.1.1.1 EMEA Based on Condition the cell would be coloured 
Switch 10.1.1.2 AMER Based on Condition the cell would be coloured 
Switch 10.1.1.3 APAC Based on Condition the cell would be coloured 
Switch 10.1.1.2 AMER Based on Condition the cell would be coloured 
Switch 10.1.1.2 AMER Based on Condition the cell would be coloured 
I’m writing each row at a time and when I want to open existing excel sheet I would pass the value i.e. _valuecolour and based its value it would colour the particular cell along with the alignment of the other cells.
I have used the code below.
public static bool InsertRowExcel(string filepath, string _sb, string _switchinput)
{
int i = 0;
string[] _arr = _switchinput.Split(',');
bool bl = false;
int k = 0;
try
{
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filepath, true))
{
//Get workbookpart
WorkbookPart workbookPart = myDoc.WorkbookPart;
WorkbookStylesPart stylePart = workbookPart.WorkbookStylesPart;
Row row = new Row();
//then access to the worksheet part
IEnumerable<WorksheetPart> worksheetPart = workbookPart.WorksheetParts;
foreach (WorksheetPart WSP in worksheetPart)
{
//find sheet data
IEnumerable<SheetData> sheetData = WSP.Worksheet.Elements<SheetData>();
// Iterate through every sheet inside Excel sheet
foreach (SheetData SD in sheetData)
{
IEnumerable<Row> rows = SD.Elements<Row>(); // Get the row IEnumerator
i = (rows.Count()); // Will give you the count of rows
do
{ row = new Row();
row.Append(
ConstructCell(_arr[0], CellValues.String),
ConstructCell(_arr[1], CellValues.String),
ConstructCell(_arr[2], CellValues.String),
ConstructCell(_sb, CellValues.String,2U)
);
}
while (k > 0);
/* HERE I NEED TO ADD STYLE TO THE CELL. */
}
}
bl = true;
}
}
catch (Exception ex)
{
bl = false;
throw ex;
}
return bl;
}
private static Stylesheet GenerateStylesheet(bool _valuecolour)
{
Stylesheet styleSheet = null;
Fills fills = new Fills();
if (_valuecolour)
{
fills = new Fills(
new Fill(new PatternFill() { PatternType = PatternValues.None }), // Index 0 - default
new Fill(new PatternFill() { PatternType = PatternValues.Gray125 }), // Index 1 - default
new Fill(new PatternFill(new ForegroundColor { Rgb = new HexBinaryValue() { Value = "FFFFFF00" } })
{ PatternType = PatternValues.Solid })
);
}
else
{
fills = new Fills(
new Fill(new PatternFill() { PatternType = PatternValues.None }), // Index 0 - default
new Fill(new PatternFill() { PatternType = PatternValues.Gray125 }), // Index 1 - default
new Fill(new PatternFill(new ForegroundColor { Rgb = new HexBinaryValue() { Value = "008000" } })
{ PatternType = PatternValues.Solid }) // Index 2 - body
);
}
CellFormats cellFormats = new CellFormats(
new CellFormat(), // default
new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
{ FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true },
new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true }){ FontId = 1, FillId = 2, BorderId = 1, ApplyFill = true }); // header
styleSheet = new Stylesheet(fills, cellFormats);
return styleSheet;
}
private static Cell ConstructCell(string value, CellValues dataType,uint styleIndex = 0)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType),
StyleIndex = styleIndex
};
}
Here is the code which works as expected
enter code here
#region ReadWriteExcel File
public static bool ReadWriteExcel(string _sb, string _switchinput, bool _checkinitial)
{
string _str = string.Empty;
bool _checkStatus = false;
bool bl = false;
String[] _arr;
_arr = _switchinput.Split(',');
int i = 0;
string filepath = _directoryPath + DateTime.Now.ToString("dd.MM.yyyy") + ".xlsx";
bl = (File.Exists(filepath) ? true : false);
if (bl) // && _checkinitial
{
//_sb = string.Empty;
//LogWrite("Just Before InsertRowExcel " + _switchinput);
_checkStatus = InsertRowExcel(filepath, _sb.ToString(), _switchinput);
}
else
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
{
try
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
worksheetPart.Worksheet = new Worksheet();
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "SAN Switch Health Check" };
sheets.Append(sheet);
stylePart.Stylesheet = GenerateStylesheetDefault();
stylePart.Stylesheet.Save();
workbookPart.Workbook.Save();
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
// Constructing header
Row row = new Row();
row.Append(
ConstructCell("Device_type", CellValues.String),
ConstructCell("Name", CellValues.String),
ConstructCell("IP Address", CellValues.String),
ConstructCell("Status", CellValues.String)
);
// Insert the header row to the Sheet Data
sheetData.AppendChild(row);
do
{
//for (int i = 0; i < _arr.Length - 1; i++)
//{
row = new Row();
row.Append(
ConstructCell(_arr[0], CellValues.String, 1U),
ConstructCell(_arr[1], CellValues.String, 1U),
ConstructCell(_arr[2], CellValues.String, 1U));//,
//ConstructCell(_sb, CellValues.String,2U));
//sheetData.AppendChild(row);
}
while (i > 0);
if (_sb != "Normal")
{
row.Append(
ConstructCell(_sb, CellValues.String, 2U));
}
else
{
row.Append(
ConstructCell(_sb, CellValues.String, 3U));
}
sheetData.AppendChild(row);
//stylePart.Stylesheet.Save();
worksheetPart.Worksheet.Save();
_checkStatus = true;
}
catch (Exception ex)
{
_checkStatus = false;
//LogWrite(ex.StackTrace.ToString());
throw ex;
}
document.Close();
document.Dispose();
}
}
return _checkStatus;
}
private static Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType),
StyleIndex = styleIndex
};
}
public static bool InsertRowExcel(string filepath, string _sb, string _switchinput)
{
// LogWrite("InsertRowExcel " + _switchinput);
int i = 0; int k = 0; bool bl = false; string[] _arr = _switchinput.Split(',');
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filepath, true))
{
//Get workbookpart
WorkbookPart workbookPart = myDoc.WorkbookPart;
WorkbookStylesPart stylePart = workbookPart.WorkbookStylesPart;
Row row = new Row();
stylePart.Stylesheet = GenerateStylesheetDefault();
stylePart.Stylesheet.Save();
//then access to the worksheet part
IEnumerable<WorksheetPart> worksheetPart = workbookPart.WorksheetParts;
foreach (WorksheetPart WSP in worksheetPart)
{//find sheet data
SheetData sheetData = WSP.Worksheet.Elements<SheetData>().First();
IEnumerable<Row> rows = sheetData.Elements<Row>(); // Get the row IEnumerator
i = (rows.Count()); // Will give you the count of rows
/* HERE I NEED TO ADD STYLE TO THE CELL on condition. */
do
{
row = new Row();
row.Append(
ConstructCell(_arr[0], CellValues.String),
ConstructCell(_arr[1], CellValues.String),
ConstructCell(_arr[2], CellValues.String)
);
if (_sb != "Normal")
{
row.Append(
ConstructCell(_sb, CellValues.String, 2U));
}
else
{
row.Append(
ConstructCell(_sb, CellValues.String, 3U));
}
sheetData.Append(row);
} while (k > 0);
}
bl = true;
myDoc.Close();
myDoc.Dispose();
}
return bl;
}
public static Stylesheet GenerateStylesheetDefault()
{
Stylesheet stylesheet1 = new Stylesheet();
Fonts fonts = new Fonts(
new Font(
new FontSize() { Val = 11D },
new Color() { Theme = (UInt32Value)1U },
new FontName() { Val = "Calibri" },
new FontFamilyNumbering() { Val = 2 },
new FontScheme() { Val = FontSchemeValues.Minor }
)
);
Borders borders = new Borders(
new Border(
new LeftBorder(),
new RightBorder(),
new TopBorder(),
new BottomBorder(),
new DiagonalBorder())
);
Fills fills = new Fills();
fills = new Fills(
new Fill(
new PatternFill() { PatternType = PatternValues.None }), //0
new Fill(
new PatternFill() { PatternType = PatternValues.Gray125 }),//1
new Fill(
new PatternFill(
new ForegroundColor { Rgb = new HexBinaryValue() { Value = "FFFFFF00" } }) //2 -yellow
{ PatternType = PatternValues.Solid }),
new Fill(
new PatternFill(
new ForegroundColor { Rgb = new HexBinaryValue() { Value = "FF008000" } })// 3 -green
{ PatternType = PatternValues.Solid })
);
CellStyleFormats cellStyleFormats = new CellStyleFormats(
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U }
);
CellFormats cellFormats = new CellFormats(
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U },
new CellFormat(
new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
{ FontId = 0, FillId = 0, BorderId = 0, ApplyAlignment = true },
new CellFormat(
new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
{ FontId = 0, FillId = 2, BorderId = 0, ApplyFill = true },
new CellFormat(
new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
{ FontId = 0, FillId = 3, BorderId = 0, ApplyFill = true }
);
stylesheet1.Append(fonts);
stylesheet1.Append(fills);
stylesheet1.Append(borders);
stylesheet1.Append(cellStyleFormats);
stylesheet1.Append(cellFormats);
return stylesheet1;
}
#endregion

DHTMLX Scheduler in mVC

I am using DHTMLX Scheduler in my MVC Application. In my scheduler when we drag and the drop the timings a popup will be displayed which is working by default scheduler.js file. My problem is while dragging the time i need to display the custom popup window. Is it possible to do with the scheduler?
Can any one please help me.
Code for scheduler is
public ActionResult CalendarView(int? id, int? CustomerUserid)
{
//id = (int)Session["BUId"];
if (CustomerUserid == (int)Session["UserID"] || (CustomerUserid == (int)Session["UserID"] && id == (int)Session["BusinessId"]))
{
var scheduler = new DHXScheduler(this);
string val = System.Configuration.ConfigurationManager.AppSettings["UserTypeId"];
int code = Convert.ToInt32(val);
//var cuid = (int)Session["UserID"];
// List<tblUser> user = new List<tblUser>();
// var user1 = (from s in user
// where s.UserTypeId == 3 && s.UserID == cuid
// select new Appt
// {
// AddCustomer = s.DependentCustomer.ToString()
// }).ToList();
var cal = (from s
in db.tblUsers
where s.UserTypeId == code && s.UserID == id
select new Appt
{
BusinessName = s.tblBusinessCategory.BusinessName
// StartTime = s.WorkingHour.StartTime,
}).FirstOrDefault();
var sa = (from a
in db.WorkHours
where a.BusinessUserId == id
select new Appt
{
StartTime = a.StartTime,
EndTime = a.EndTime
}).FirstOrDefault();
Session["StartTime"] = sa.StartTime.Hour;
Session["EndTime"] = sa.EndTime.Hour;
Session["BUName"] = cal.BusinessName.ToString();
// var scheduler = new DHXScheduler(this);//{ InitialDate = new DateTime(2015, 1, 30) };
scheduler.Skin = DHXScheduler.Skins.Flat;
scheduler.Data.Loader.PreventCache();
scheduler.EnableDynamicLoading(SchedulerDataLoader.DynamicalLoadingMode.Week);
scheduler.Extensions.Add(SchedulerExtensions.Extension.Recurring);
//scheduler.Extensions.Add(SchedulerExtensions.Extension.ActiveLinks);
//scheduler.Extensions.Add(SchedulerExtensions.Extension.Collision);
scheduler.Extensions.Add(SchedulerExtensions.Extension.Limit);
scheduler.Config.limit_start = new DateTime(2015, 8, 25);
scheduler.Config.limit_end = new DateTime(2015, 9, 25);
scheduler.LoadData = true;
scheduler.EnableDataprocessor = true;
scheduler.Config.show_loading = true;
// scheduler.Config.buttons_left = ["dhx_save_btn","dhx_cancel_btn","locate_button"];
//var button = new LightboxButtonList();
//scheduler.Lightbox.Add();
int days = System.DateTime.Now.Day - 1;
int months = System.DateTime.Now.Month;
int years = System.DateTime.Now.Year;
int ihour = System.DateTime.Now.Hour;
int iminute = System.DateTime.Now.Minute;
int isecond = System.DateTime.Now.Second;
scheduler.TimeSpans.Add(new DHXBlockTime()
{
StartDate = new DateTime(2014, 2, 10),
EndDate = new DateTime(years, months, days + 1, ihour, iminute, isecond),
});
Session["BUId"] = id;
var parameter = new SqlParameter[1];
parameter[0] = new SqlParameter { ParameterName = "UserId", Value = id };
List<Appt> cm = new List<Appt>();
using (SYTEntities context = new SYTEntities())
{
cm = context.Database.SqlQuery<Appt>("exec spHoliday #UserId", parameter).ToList();
}
int iyear = 2015;
int imonth = 8;
int iday = 09;
//int ihour = 10;
int imin = 05;
int isec = 00;
foreach (var cp in cm)
{
iyear = cp.HolidayDate.Year;
imonth = cp.HolidayDate.Month;
iday = cp.HolidayDate.Day;
scheduler.TimeSpans.Add(new DHXMarkTime()
{
StartDate = new DateTime(iyear, imonth, iday), //new DateTime(2015, 8, 06), //hl.HolidayDate ?? default(DateTime),
EndDate = new DateTime(iyear, imonth, iday + 1),
// Day = DayOfWeek.Friday,
CssClass = "red_section",
HTML = "hos",
SpanType = DHXTimeSpan.Type.BlockEvents
});
}
var parameters = new SqlParameter[1];
parameters[0] = new SqlParameter { ParameterName = "BusinessUserId", Value = id };
List<Appt> wt = new List<Appt>();
using (SYTEntities context = new SYTEntities())
{
wt = context.Database.SqlQuery<Appt>("exec spGetWaitingList #BusinessUserId", parameters).ToList();
}
int ihr;
int imts;
int idayd;
int iyr;
int imnth;
int ihrs;
foreach (var cs in wt)
{
iyr = cs.EndTime.Year;// System.DateTime.Now.Year;
imnth = cs.EndTime.Month;// System.DateTime.Now.Month;
idayd = cs.EndTime.Day;// System.DateTime.Now.Day;
ihr = cs.EndTime.Hour; //.Hours; //.Hour;
imts = cs.EndTime.Minute; //.Minutes; //.Minute;
isec = cs.EndTime.Second; //.Seconds;
ihrs = cs.EndTime.Hour - cs.StartTime.Hour;
scheduler.TimeSpans.Add(new DHXMarkTime()
{
StartDate = new DateTime(iyr, imnth, idayd, ihr, imts, isec), //new DateTime(2015, 8, 06), //hl.HolidayDate ?? default(DateTime),
EndDate = new DateTime(iyr, imnth, idayd, ihr, imts, isec),
// Day = DayOfWeek.Friday,
CssClass = "green_section",
HTML = "",
SpanType = DHXTimeSpan.Type.BlockEvents
});
}
//for (int i = 0; i < 4; i++)
//{
// scheduler.TimeSpans.Add(new DHXMarkTime()
// {
// StartDate = new DateTime(iyear, imonth,iday,ihour, imin, isec), //new DateTime(2015, 8, 06), //hl.HolidayDate ?? default(DateTime),
// EndDate = new DateTime(iyear, imonth, iday,ihour, imin, isec),
// CssClass = "red_section",
// SpanType = DHXTimeSpan.Type.BlockEvents
// });
//}
scheduler.BeforeInit.Add("schedulerClient.init()");
//var check = new LightboxCheckbox("highlighting", "Important") { MapTo = "color", CheckedValue = "#FE7510" };
//scheduler.Lightbox.Add(check);
return View(scheduler);
}
return View();
}
Image
Do you mean you need to show some kind of popup showing additional info during task move/resize?
If so, you can use template for task content - if the current task is being dragged or resized, a template should return an absolute positioned popup with a custom content
E.g.
JS:
scheduler.attachEvent("onSchedulerReady", function () {
var headerTemplate = scheduler.templates.event_header;
scheduler.templates.event_header = function (start, end, event) {
var content = headerTemplate(start, end, event);
if (scheduler.getState().drag_id == event.id) {
var dragPopup = "<div class='drag-popup'>" + headerTemplate(start, end, event) + "</div>";
content += dragPopup;
}
return content;
};
});
CSS:
.drag-popup{
position: absolute;
right:0;
top: 0;
margin-right: 120px;
padding: 10px;
width: 100px;
background-color: inherit;
color: inherit;
z-index: 5;
}
Result:
Although, with this approach you'll need to manage tooltip position more thoughtfully than i did in this sample. Since popup is nested in event's DOM element, it will be limited by a scheduler container. E.g. when event is in left-most column - you'll need to locate popup at right, otherwise it will be cutted.
Here are the related API methods
http://docs.dhtmlx.com/scheduler/api__scheduler_getstate.html
http://docs.dhtmlx.com/scheduler/api__scheduler_event_header_template.html

Iterate through collection of List<object>

I have what is probably simple problem, but I am stumped. I call a method from another assembly that returns me a List<object>, this data is Excel spreadsheet data queried using LinqToExcel. Under the scenes, that collection is actually a List<LinqToExcel.Cell>. In LinqToExcel, that makes up a LinqToExcel.Row. I want to be able to bind this data to a Telerik ASP.NET MVC grid for viewing. Here's my controller code:
TypeOfServiceCodeListingDetailViewModel model = new TypeOfServiceCodeListingDetailViewModel();
model.Excel_Data = new List<LinqToExcel.Row>();
using (LinqToExcelReader reader = new LinqToExcelReader(fileName, true))
{
previewData = reader.ReadRawDataByPage(5, 0);
foreach (LinqToExcel.Row item in previewData)
{
model.Excel_Data.Add(item);
}
return View(new GridModel(model.Excel_Data));
}
And in my view:
#(Html.Telerik().Grid(Model.Excel_Data)
.Name("Grid2")
.HtmlAttributes(new { style = "width:400px;" })
.DataBinding(dataBinding => dataBinding.Ajax().Select("GetExcelData", "TypeOfService"))
.Columns(columns =>
{
columns.AutoGenerate(column =>
{
column.Width = "150px";
});
}))
Here's what my grid has headers like the below with no data:
Capacity Count
Thanks for the help!
Here's the code that solved my problem. I'm sure there's a better approach.
using (LinqToExcelReader reader = new LinqToExcelReader(modelDetail.FileName, true))
{
var previewData = reader.ReadRawDataByPage(5, 0);
List<List<string>> masterList = new List<List<string>>();
for (int x = 0; x < previewData.Count; x++)
{
List<string> list = new List<string>();
foreach (var cell in (LinqToExcel.Row)previewData[x])
{
list.Add(cell);
}
masterList.Add(list);
}
var listTest = masterList;
modelDetail.ExcelData = new List<ExcelData>();
foreach (List<string> theList in masterList)
{
ExcelData xlsData = new ExcelData();
xlsData.Column1 = theList[0];
xlsData.Column2 = theList[1];
xlsData.Column3 = theList[2];
xlsData.Column4 = theList[3];
xlsData.Column5 = theList[4];
xlsData.Column6 = theList[5];
xlsData.Column7 = theList[6];
xlsData.Column8 = theList[7];
xlsData.Column9 = theList[8];
xlsData.Column10 = theList[9];
modelDetail.ExcelData.Add(xlsData);
}