Colouring Excel cell with condition using DocumentFormat.OpenXml - spreadsheet

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

Related

Android MPAndroidChart xAxis.setValueFormatter throws ArrayIndexOutOfBoundsException

Good morning,
I'm struggling with ArrayIndexOutOfBoundsException thrown when i'm inserting the row
xAxis.setValueFormatter(formatter) (commented in code).
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bc = findViewById(R.id.chart);
CaricaStorico cs = new CaricaStorico();
try {
cs.execute().get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
List<BarEntry> turno1 = new ArrayList<>();
List<BarEntry> turno2 = new ArrayList<>();
List<BarEntry> turno3 = new ArrayList<>();
String[] date = new String[100];
boolean datiturno1 = false;
boolean datiturno2 = false;
boolean datiturno3 = false;
for (int i = 0; i < storicoMacchina.size(); i++) {
Storico st = storicoMacchina.get(i);
System.out.println(st.getData() + " - " + st.getProduzione1() + " - " + st.getProduzione2() + " - " + st.getProduzione3());
turno1.add(new BarEntry(i, st.getProduzione1()));
turno2.add(new BarEntry(i, st.getProduzione2()));
turno3.add(new BarEntry(i, st.getProduzione3()));
if (st.getProduzione1() != 0) {
datiturno1 = true;
}
if (st.getProduzione2() != 0) {
datiturno2 = true;
}
if (st.getProduzione3() != 0) {
datiturno3 = true;
}
Calendar c = Calendar.getInstance();
c.setTime(st.getData());
String dataMese = c.get(Calendar.DAY_OF_MONTH) + "/" + (c.get(Calendar.MONTH) + 1);
xLabels.add(dataMese);
}
ValueFormatter formatter = new ValueFormatter() {
#Override
public String getAxisLabel(float value, AxisBase axis) {
return xLabels.get((int) value);
}
};
BarDataSet set1 = null;
BarDataSet set2 = null;
BarDataSet set3 = null;
set1 = new BarDataSet(turno1, "Turno 1");
set2 = new BarDataSet(turno2, "Turno 2");
set3 = new BarDataSet(turno3, "Turno 3");
System.out.println(datiturno1 + "," + datiturno2 + "," + datiturno3);
float groupSpace = 0.04f;
float barSpace = 0.02f;
float barWidth = 0.3f;
// set1.setColors(new int[] { R.color.red, R.color.red1, R.color.red2, R.color.red3 },MainActivity.this);
set1.setColor(getResources().getColor(R.color.turno1));
set2.setColor(getResources().getColor(R.color.turno2));
set3.setColor(getResources().getColor(R.color.turno3));
BarData barData;
if (datiturno3 == false) {
barData = new BarData(set1, set2);
groupSpace = 0.06f;
barSpace = 0.02f;
barWidth = 0.45f;
} else {
barData = new BarData(set1, set2, set3);
}
barData.setBarWidth(barWidth);
bc.setData(barData);
Description desc = new Description();
desc.setText("Produzione ultima settimana");
bc.setDescription(desc);
bc.groupBars(0, groupSpace, barSpace);
XAxis xAxis = bc.getXAxis();
xAxis.setCenterAxisLabels(true);
xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1);
xAxis.setAxisMaximum(storicoMacchina.size());
// xAxis.setValueFormatter(formatter);
bc.invalidate();
}
without this line code is working fine except for the labels in xAxis that i'm trying to set with this line.
Anyone can help me to find what i'm doing wrong?
Thank you for your help
your text
I'have found workaround to solve my problem changing the code above with this
If anyone can explain me the reason value index differs from my xlabel, dataset size will be appreciated.
Thanks again
public String getAxisLabel(float value, AxisBase axis) {
String label = "";
if ((value >= 0) && (value <= xLabels.size() -1)) {
label = xLabels.get((int) value);
}
return label;
}

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

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:

Label Printing using iTextSharp

I have a logic to export avery label pdf. The logic exports the pdf with labels properly but when i print that pdf, the page size measurements (Page properties) that i pass isn't matching with the printed page.
Page Properties
Width="48.5" Height="25.4" HorizontalGapWidth="0" VerticalGapHeight="0" PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8" PageSize="A4" LabelsPerRow="4" LabelRowsPerPage="10"
The above property values are converted equivalent to point values first before applied.
Convert to point
private float mmToPoint(double mm)
{
return (float)((mm / 25.4) * 72);
}
Logic
public Stream SecLabelType(LabelProp _label)
{
List<LabelModelClass> Model = new List<LabelModelClass>();
Model = RetModel(_label);
bool IncludeLabelBorders = false;
FontFactory.RegisterDirectories();
Rectangle pageSize;
switch (_label.PageSize)
{
case "A4":
pageSize = iTextSharp.text.PageSize.A4;
break;
default:
pageSize = iTextSharp.text.PageSize.A4;
break;
}
var doc = new Document(pageSize,
_label.PageMarginLeft,
_label.PageMarginRight,
_label.PageMarginTop,
_label.PageMarginBottom);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, output);
writer.CloseStream = false;
doc.Open();
var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
var tbl = new PdfPTable(numOfCols);
var colWidths = new List<float>();
for (int i = 1; i <= numOfCols; i++)
{
if (i % 2 > 0)
{
colWidths.Add(_label.Width);
}
else
{
colWidths.Add(_label.HorizontalGapWidth);
}
}
var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
var size = new iTextSharp.text.Rectangle(w, h);
tbl.SetWidthPercentage(colWidths.ToArray(), size);
//var val = System.IO.File.ReadLines("C:\\Users\\lenovo\\Desktop\\test stock\\testing3.txt").ToArray();
//var ItemNoArr = Model.Select(ds => ds.ItemNo).ToArray();
//string Header = Model.Select(ds => ds.Header).FirstOrDefault();
int cnt = 0;
bool b = false;
int iAddRows = 1;
for (int iRow = 0; iRow < ((Model.Count() / _label.LabelsPerRow) + iAddRows); iRow++)
{
var rowCells = new List<PdfPCell>();
for (int iCol = 1; iCol <= numOfCols; iCol++)
{
if (Model.Count() > cnt)
{
if (iCol % 2 > 0)
{
var cellContent = new Phrase();
if (((iRow + 1) >= _label.StartRow && (iCol) >= (_label.StartColumn + (_label.StartColumn - 1))) || b)
{
b = true;
try
{
var StrArr = _label.SpineLblFormat.Split('|');
foreach (var x in StrArr)
{
string Value = "";
if (x.Contains(","))
{
var StrCommaArr = x.Split(',');
foreach (var y in StrCommaArr)
{
if (y != "")
{
Value = ChunckText(cnt, Model, y, Value);
}
}
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
else
{
Value = ChunckText(cnt, Model, x, Value);
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
}
}
catch (Exception e)
{
var fontHeader1 = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 6, 0);
cellContent.Add(new Chunk("NA", fontHeader1));
}
cnt += 1;
}
else
iAddRows += 1;
var cell = new PdfPCell(cellContent);
cell.FixedHeight = _label.Height;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;
rowCells.Add(cell);
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
_label.LabelRowsPerPage = _label.LabelRowsPerPage == null ? 0 : _label.LabelRowsPerPage;
if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
{
tbl.Rows.Add(CreateGapRow(numOfCols, _label));
}
}
doc.Add(tbl);
doc.Close();
output.Position = 0;
return output;
}
private PdfPRow CreateGapRow(int numOfCols, LabelProp _label)
{
var cells = new List<PdfPCell>();
for (int i = 0; i < numOfCols; i++)
{
var cell = new PdfPCell();
cell.FixedHeight = _label.VerticalGapHeight;
cell.Border = Rectangle.NO_BORDER;
cells.Add(cell);
}
return new PdfPRow(cells.ToArray());
}
A PDF document may have very accurate measurements, but then those measurements get screwed up because the page is scaled during the printing process. That is a common problem: different printers will use different scaling factors with different results when you print the document using different printers.
How to avoid this?
In the print dialog of Adobe Reader, you can choose how the printer should behave:
By default, the printer will try to "Fit" the content on the page, but as not every printer can physically use the full page size (due to hardware limitations), there's a high chance the printer will scale the page down if you use "Fit".
It's better to choose the option "Actual size". The downside of using this option is that some content may get lost because it's too close to the border of the page in an area that physically can't be reached by the printer, but the advantage is that the measurements will be preserved.
You can set this option programmatically in your document by telling the document it shouldn't scale:
writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
See How to set initial view properties? for more info about viewer preferences.

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

Component One pdf generation using draw image crashing if printing pdf pages more than 40

I'm using below code to generate pdf of a page having listview. And it all works good till I have a very small list once I got list with more than 50 items it crashing with memory exception. I think variable pdf is taking all memory. I have checked using profiling it goes above 180 and pdf variable was on top when I took snapshot at profile.
async PDFTest_Loaded(int a)
{
try
{
pdf = new C1PdfDocument(PaperKind.Letter);
pdf.Compression = CompressionLevel.NoCompression;
WriteableBitmap writeableBmp = await initializeImage();
List<WriteableBitmap> ListBitmaps = new List<WriteableBitmap>();
pdfPage PageBitmaps = new pdfPage();
FrameworkElement header = RTABlock as FrameworkElement;
header.Arrange(pdf.PageRectangle);
var headerImage = await CreateBitmap(header);
FrameworkElement Pageheader = SalikPaymentReceipt as FrameworkElement;
Pageheader.Arrange(pdf.PageRectangle);
var PageHeaderImage = await CreateBitmap(Pageheader);
double pdfImageWidth = 0;
foreach (var item in EpayPreviewListView.Items)
{
List<WriteableBitmap> temp = new List<WriteableBitmap>();
var obj = EpayPreviewListView.ContainerFromItem(item);
List<FrameworkElement> controls = Children(obj);
StackPanel ListItemStackPanel = controls.Where(x => x is StackPanel && x.Name == "ListItemStackPanel").First() as StackPanel;
if (ListItemStackPanel is StackPanel)
{
StackPanel itemui = ListItemStackPanel as StackPanel;
if (!(pdfImageWidth > 0))
{
pdfImageWidth = itemui.ActualWidth;
}
itemui.Arrange(new Rect(0, 0, pdfImageWidth, pdf.PageRectangle.Height));
temp.Add(await CreateBitmap(itemui));
PageBitmaps = new pdfPage() { bitmap = temp };
CreateDocumentText(pdf, headerImage, writeableBmp, PageHeaderImage, PageBitmaps);
PageBitmaps = null;
temp = new List<WriteableBitmap>();
}
}
StorageFile Assets = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Salik Payment Receipts.pdf", CreationCollisionOption.GenerateUniqueName);
PdfUtils.Save(pdf, Assets);
EpayPreviewListView.InvalidateArrange();
EpayPreviewListView.UpdateLayout();
LoadingProgress.Visibility = Visibility.Collapsed;
PrintButton.IsEnabled = true;
}
catch (Exception ex)
{
Debugger.Break();
}
}
public List<FrameworkElement> Children(DependencyObject parent)
{
try
{
var list = new List<FrameworkElement>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is StackPanel || child is TextBlock || child is ListView)
list.Add(child as FrameworkElement);
list.AddRange(Children(child));
}
return list;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString() + "\n\n" + e.StackTrace);
Debugger.Break();
return null;
}
}
async public Task<WriteableBitmap> CreateBitmap(FrameworkElement element)
{
// render element to image (WinRT)
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element);
var wb = new WriteableBitmap(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);
(await renderTargetBitmap.GetPixelsAsync()).CopyTo(wb.PixelBuffer);
//var rect = new Rect(0, 0, renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);
if (!App.IsEnglishSelected)
{
wb = wb.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
}
return wb;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString() + "\n\n" + ex.StackTrace);
Debugger.Break();
return new WriteableBitmap(0, 0);
}
}
bool isFirst = true;
void CreateDocumentText(C1PdfDocument pdf, WriteableBitmap headerImage, WriteableBitmap writeableBmp, WriteableBitmap pageHeading, pdfPage ListItem)
{
try
{
if (!isFirst)
{
pdf.NewPage();
}
isFirst = false;
pdf.Landscape = false;
double contentHeight = 0;
double leftMargin = 0;
string fontName = "Arial";
// measure and show some text
var text = App.GetResource("RoadandTransportAuthority");
var font = new Font(fontName, 36, PdfFontStyle.Bold);
// create StringFormat used to set text alignment and line spacing
var fmt = new StringFormat();
fmt.Alignment = HorizontalAlignment.Center;
var rc = new Rect(0, 0,
pdf.PageRectangle.Width, headerImage.PixelHeight);
pdf.DrawImage(headerImage, rc, ContentAlignment.MiddleCenter, Stretch.None);
contentHeight += headerImage.PixelHeight + 2;
rc = new Rect(0, contentHeight, pdf.PageRectangle.Width, writeableBmp.PixelHeight);
pdf.DrawImage(writeableBmp, rc);
contentHeight += writeableBmp.PixelHeight + 5;
rc = new Rect(leftMargin, contentHeight,
pdf.PageRectangle.Width,
pageHeading.PixelHeight);
pdf.DrawImage(pageHeading, rc, ContentAlignment.MiddleCenter, Stretch.None);
contentHeight += pageHeading.PixelHeight + 2;
Debug.WriteLine(ListItem.bitmap.Count.ToString());
for (int i = 0; i < ListItem.bitmap.Count; i++)
{
rc = PdfUtils.Offset(rc, 0, rc.Height + 10);
rc.Height = ListItem.bitmap.ElementAt(i).PixelHeight;
pdf.DrawImage(ListItem.bitmap.ElementAt(i), rc, ContentAlignment.TopCenter, Stretch.None);
ListItem.bitmap[i] = null;
}
ListItem = null;
}
catch (Exception e)
{
//...
}
}
It is due to memory clash I have to decrease the quality of images to handle it. Also it takes some time to release memory.