EPPlus two color conditional date format - epplus

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);
}
}
}

Related

How to find empty rows from excel sheet given by user and delete them in asp.net

public async Task<List<IndiaCIT>> Import(IFormFile file)
{
var list = new List<IndiaCIT>();
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package=new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowcount = worksheet.Dimension.Rows;
for (int row = 1; row <= rowcount; row++)
{
list.Add(new IndiaCIT {
NameCH = worksheet.Cells[row, 1].Value.ToString().Trim(),
City= worksheet.Cells[row, 2].Value.ToString().Trim(),
Age = worksheet.Cells[row, 3].Value.ToString().Trim(),
});
}
}
}
return list;
}
this is controller code and in model class declared the columns name and used it as IndiaCIT list in controller,. I want empty rows to get deleted
This could help:
For each row in the sheet, check if the cell in each column is empty. If so delete it.
var rowcount = worksheet.Dimension.Rows;
var maxColums = worksheet.Dimension.Columns;
for(int row = rowcount; row > 0; row--)
{
bool isRowEmpty = true;
for(int column = 1; column <= maxColumns; column++)
{
var cellEntry = worksheet.Cells[row, column].Value.ToString();
if(!string.IsNullOrEmpty(cellEntry)
{
isRowEmpty = false;
break;
}
}
if(!isRowEmpty)
continue;
else
worksheet.DeleteRow(row);
}
I generally use Spire.Xls to handle such problems. It works for me.
public IActionResult Test() {
//init workbook
Workbook workbook = new Workbook();
// load file
workbook.LoadFromFile("11.xlsx");
// get the first sheet
Worksheet sheet = workbook.Worksheets[0];
//delete blank row
for (int i = sheet.Rows.Count() - 1; i >= 0; i--)
{
if (sheet.Rows[i].IsBlank)
{
sheet.DeleteRow(i + 1);
}
}
//delete blank column
for (int j = sheet.Columns.Count() - 1; j >= 0; j--)
{
if (sheet.Columns[j].IsBlank)
{
sheet.DeleteColumn(j + 1);
}
}
//save as a new xls file
workbook.SaveToFile("new.xlsx", ExcelVersion.Version2016);
return Ok();
}

how do I change this google app script to hide sheets columns instead of rows based on column dates

so I'm a long way form a competent programmer, but I do dabble in google sheets scripts.
I previously had a script running on a timer trigger to hide rows based on dates found in column A.
function min() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("OLD");
var v = s.getRange("A:A").getValues();
var today = new Date().getTime() - 86400000‬
for (var i = s.getLastRow(); i > 1; i--) {
var t = v[i - 1];
if (t != "") {
var u = new Date(t);
if (u < today) {
s.hideRows(i);
}
}
}
}
function max() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("OLD");
var v = s.getRange("A:A").getValues();
var today = new Date().getTime() + 86400000
for (var i = s.getLastRow(); i > 1; i--) {
var t = v[i - 1];
if (t != "") {
var u = new Date(t);
if (u > today) {
s.hideRows(i);
}
}
}
}
function SHOWROWS() {
// set up spreadsheet and sheet
var ss = SpreadsheetApp.getActiveSpreadsheet(), sheets = ss.getSheets();
for(var i = 0, iLen = sheets.length; i < iLen; i++) {
// get sheet
var sh = sheets[i];
// unhide rows
var rRows = sh.getRange("A:A");
sh.unhideRow(rRows);
}
}
this would be set to run at midnight every night so as to hide all rows not +-1 day from the current date.
I have now switched to using this document primarily through the android app I need to swap the input layout Moving dates from rows and values in columns to the inverse, values are now in rows and the dates are in columns, inputing vertical values would be much quicker....but honestly its more about understanding what im doing wrong thats really motivating my search for a answer.
can anyone help me modify my old script to work on this changed sheet.
my attempts fall flat..eg:
function min() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("OLD");
var v = s.getRange("1:1").getValues();
var today = new Date().getTime() - 86400000‬
for (var i = s.getLastColumn(); i > 1; i--) {
var t = v[i - 1];
if (t != "") {
var u = new Date(t);
if (u < today) {
s.hidecolumns(i);
}
}
}
}
example spreadsheet:
https://docs.google.com/spreadsheets/d/1EjRIeDPrG_qp1S9QhInl9r3G0cZx_16OvnTXORgA3n4/edit?usp=sharing
there is two sheets one with the old version of my layout called "OLD" and my new desired layout called "NEW"
thanks in advance to anyone able to help
This function hides a column whose top row date is less yesterday.
function hideColumnWhenTopRowDateIsBeforeYesterday() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sh=ss.getSheetByName("Sheet1");
var rg=sh.getRange(1,1,1,sh.getLastColumn());
var vA=rg.getValues()[0];
var yesterday=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()-1).valueOf();
vA.forEach(function(e,i){
if(new Date(e).valueOf()<yesterday) {
sh.hideColumns(i+1);
}
});
}
My Spreadsheet before hiding columns:
My Spreadsheet after hiding columns:

Why the last empty row has been pulled as an additional test with null values in selenium apache POI

I have four rows in an excel, first row is for the heading and rest of the three rows has values in it. I have entered the code in a way to avoid the header and read the rows which contains values only. However instead of fetching only three rows it comes with one additional null value rows as below, Why it is fetching the null values did I miss anything? Find the code and error message.
Message
PASSED: testShipment("Mumbai", "New York", "18000", "10000", "20000")
PASSED: testShipment("Mumbai", "Cochin", "2000", "30000", "5000")
PASSED: testShipment("Cochin", "Farah", "16000", "18000", "19000")
FAILED: testShipment(null, null, null, null, null)
Code
int TotalCol = sh.getRow(0).getLastCellNum();
int Totalrows = sh.getLastRowNum()+1;
String[][] data = new String[Totalrows][TotalCol];
DataFormatter formatter = new DataFormatter(); // creating formatter using the default locale
for (int i = 1; i < Totalrows; i++) {
Row r = sh.getRow(i);
for (int j = 0; j < TotalCol; j++) {
Cell c = r.getCell(j);
try {
if (c.getCellType() == Cell.CELL_TYPE_STRING) {
String j_username = formatter.formatCellValue(c);
data[i][j] = j_username;
System.out.println("data[i][j]" + data[i][j]);
} else {
data[i][j] = String.valueOf(c.getNumericCellValue());
String j_username = formatter.formatCellValue(c);
data[i][j] = j_username;
System.out.println("data[i][j] numeric val" + data[i][j]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try with the below code like checking null condition
for (int k = 1; k <= totalRows; k++) {
String testCaseID = sheet.getRow(k).getCell(0).getStringCellValue();
if (testCaseID.equalsIgnoreCase(tcID)) {
for (int l = 1; l < totalCols; l++) {
String testData_FieldName = sheet.getRow(0).getCell(l).getStringCellValue();
if (testData_FieldName.equalsIgnoreCase(header)) {
cell = sheet.getRow(k).getCell(l);
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:// numeric value in excel
result = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING: // string value in excel
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN: // boolean value in excel
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK: // blank value in excel
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: // Error value in excel
result = cell.getErrorCellValue() + "";
break;
default:
throw new CustomException("The cell data type is invalid");
}
}
}
}
k = totalRows + 1;
}
}
You need to change either the data array declaration part or Totalrows calculation part. Currently, you have created 4 rows object and only 3 rows values are assigned and hence 4th row values are holding null value.
String[][] data = new String[Totalrows][TotalCol];
In your string array, you are not persisting the header value and storing only values. So, please modify your code with any one of the below options (I would suggest you to use option 1)
Option 1:
Remove the +1 from Totalrows variable and add the equal condition in your first for loop
//Removed the +1
int Totalrows = sh.getLastRowNum();
String[][] data = new String[Totalrows][TotalCol];
DataFormatter formatter = new DataFormatter(); // creating formatter using the default locale
//Condition is modified as i <= Totalrows
for (int i = 1; i <= Totalrows; i++) {
Option 2:
Change the data[][] declaration part
int Totalrows = sh.getLastRowNum()+1;
String[][] data = new String[Totalrows-1][TotalCol];
Here is the code that works, thanks to everyone for helping on this!
int TotalCol = sh.getRow(0).getLastCellNum();
int Totalrows = sh.getLastRowNum()+1;
//Entering minus one(-1) during data declaration ignores the first row as first row is a header
String[][] data = new String[Totalrows-1][TotalCol];
DataFormatter formatter = new DataFormatter(); // creating formatter using the default locale
for (int i = 1; i <Totalrows; i++) {
Row r = sh.getRow(i);
for (int j = 0; j < TotalCol; j++) {
Cell c = r.getCell(j);
try {
if (c.getCellType() == Cell.CELL_TYPE_STRING) {
String j_username = formatter.formatCellValue(c);
//Adding minus on(data[i-1]) helps to read the first cell which is (0,1), in this case (0,1) would not read the header since we have skipping the header from the table in the previous step on top, therefore the actual table starts from the second row.
data[i-1][j] = j_username;
System.out.println("data[i-1][j]" + data[i-1][j]);
} else {
data[i-1][j] = String.valueOf(c.getNumericCellValue());
String j_username = formatter.formatCellValue(c);
data[i-1][j] = j_username;
System.out.println("data[i-1][j] numeric val" + data[i-1][j]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
"

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.

Sending emails from a spreadsheet

I grabbed this script from: https://developers.google.com/apps-script/articles/sending_emails
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var emailSent = row[2]; // Third column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
I'm wondering if I would be able to make a dynamic subject line (per email). Is that possible?
Thank you!
James
Sure. Assuming that you put the value of the subject in the next column (D from you example), just do something like the following:
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var emailSent = row[2]; // Third column
var subject = row[3];
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}