EPPlus - How to set data type of a column to General - asp.net-core

In my ASP.NET Core 1.1 app I'm using EPPlus.Core to export data to Excel. Some columns exported have mostly numbers but rarely a text (e.g. N/A). These columns in generated Excel are showing (as expected) a green triangle on the top left corner of their cells. I want to get rid of those warnings.
Question: What's a good way of getting rid of those triangles when Excel is generated? I tried setting the format of these columns to text as follows but it did not work. I guess we need to set the format of these columns to General but I can't figure out how:
workSheet.Cells["D1:P1"].Style.Numberformat.Format = "General";
UPDATE:
Per a user's request, the code looks similar to following.
Error at inner loop for (var j = 4; j < testlist[i].Count(); j++){...}: MyViewModel does not contain a definition of Count()
Error at line if (testlist[i][j] is string){...}: cannot apply indexing with [] to an extension of type MyViewModel
Controller:
....
....
var testlist = (qry to load a MyViewModel).ToList();
using (ExcelPackage pkg= new ExcelPackage())
{
var ws = excel.Workbook.Worksheets.Add("TestWorkSheet");
ws.Cells[1, 1].LoadFromCollection(rc_excel, true);
//I'm starting from 2nd row and 5th column
for (var i = 1; i < testlist.Count; i++)
{
for (var j = 4; j < testlist[i].Count(); j++)
{
if (testlist[i][j] is string)
{
....
....
}
}
pkg.Save();
return(....);
}

Related

Is it possible to batch process range protections in Google Apps Script?

I have to create a dozen protected ranges in a sheet. I have code that works but is very slow because it contacts the server for each range. I know it's possible to work on a local copy of the data if there's some cell processing involved. Is it possible for range protections also?
If it's not, would caching help?
The below code uses the username from the first row as an editor for a bunch of rows in the same column.
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheets = spreadSheet.getSheets();
//Set protections per column, we start from the 4th.
for (var i = 4; i <= sheets[3].getLastColumn(); i++){
///Get the username.
var editor = sheets[3].getRange(1, i).getDisplayValue();
//Set the protection.
var protection = sheets[3].getRange(3, i, 22, 1).protect();
protection.setDescription(editor);
//Handle the case of deleted/unknown usernames.
try{
protection.addEditor(editor + '#domain.com');
} catch(error){
protection.addEditor('user#domain.com');
}
}
I've found a solution for a similar issue https://stackoverflow.com/a/37820854 but when I try to apply it to my case I get an error "TypeError: Cannot find function getRange in object Range" so I must be doing something wrong.
var test = [];
for (var i = 4; i <= sheets[3].getLastColumn(); i++){
test.push(sheets[3].getRange(3, i, 22, 1));
}
var editor;
for (var i = 0; i<test.length; i++){
var editor = test[i].getRange(1, 1).getDisplayValue();
}
The syntax for the method getRange() is getRange(row, column, numRows, numColumns), while you counter variable i loops through the COLUMNS instead of ROWS.
If your intention is to loop through all columns and add an editor to each one, it should be something like
for (var i = 4; i <= sheets[3].getLastColumn(); i++){
///Get the username.
var editor = sheets[3].getRange(1, i).getDisplayValue();
//Set the protection.
var protection = sheets[3].getRange(startRow, i, rowNumber, columnNumber).protect();
protection.setDescription(editor);
//Handle the case of deleted/unknown usernames.
try{
protection.addEditor(editor + '#domain.com');
} catch(error){
protection.addEditor('user#domain.com');
}
}
Its possible to do batch processing.
But you'll have to use Advanced Google Services. Check out the Sheets Advanced service and the Sheets API documentation.

Workbook cell style in POI/NPOI doesn't work properly with multiple styles in workbook

I'm running into strange problem with .Net version of POI library for Excel Spreadsheets. I'm rewriting from text files to Excel 97-2003 documents and I'm like to add some formatting programmatically depend on some values gather at the begging of the program.
At the beginning, in the same method where I was creating a new cell from given value I was creating also a new Workbook CellStyle which was wrong, because I was running out of the styles very quickly (or I was just thought it was the cause of the problem).
Constructor of the class responsible for Excel Workbook:
public OldExcelWriter(TextWriter logger) : base(logger)
{
_workbook = new HSSFWorkbook();
_sheetData = _workbook.CreateSheet("sheet1");
_creationHelper = _workbook.GetCreationHelper();
}
Method that is calling all the chains of operations:
public void Write(string path, Data data)
{
FillSpreadSheetWithData(data, _sheetData);
SaveSpreadSheet(_workbook, path);
}
Long story short, in FillSpreadSheetWithData I have method for creating a row inside which I'm have a loop for each cell, so basically I'm iterating thru every column, passing IRow references to a row, column value, index and formatting information like this:
for (int j = 0; j < column.Count; j++)
{
CreateCell(row, column[j], j, data.Formatting[j]);
}
and while creating a new styles (for first shot I was trying to pass some date time values) I had situation like this in my rewrited Excel: screenshot of excel workbook
So formatting was passed correctly (also Horizontal Aligment etc.) but it get ugly after 15th row (always the same amount).
DateTime dataCell = DateTime.MaxValue;
var cell = row.CreateCell(columnIndex);
_cellStyle = _workbook.CreateCellStyle();
switch (format.Type)
{
case DataType.Date:
_cellStyle.DataFormat = _creationHelper.CreateDataFormat().GetFormat("m/dd/yyyy");
if (value.Replace("\n", "") != string.Empty)
{
dataCell = DateTime.ParseExact(value.Replace("\n", ""), "m/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
}
break;
}
switch (format.HorizontalAlignment)
{
case Enums.HorizontalAlignment.Left:
_cellStyle.Alignment = HorizontalAlignment.LEFT;
break;
case Enums.HorizontalAlignment.Center:
_cellStyle.Alignment = HorizontalAlignment.CENTER;
break;
}
if (dataCell != DateTime.MaxValue)
{
cell.CellStyle = _cellStyle;
cell.SetCellValue(dataCell);
dataCell = DateTime.MaxValue;
}
else
{
cell.CellStyle = _cellStyle;
cell.SetCellValue(value);
}
(It's not the cleanest code but I will don refactor after getting this work).
After running into this issue I thought that maybe I will create _cellStyle variable in the constructor and only change it's value depends on the case, because it's assigned to the new cell anyway and I see while debugging that object values are correct.
But after creating everything, it won't get any better. Styles was override by the last value of the style, and dates are spoiled also, but later: screnshoot of excel workbook after creating one instance of cell style
I'm running out of ideas, maybe I should create every combination of the cell styles (I'm using only few data formats and alignments) but before I will do that (because I'm running out of easy options right now) I wonder what you guys think that should be done here.
cell format is set to custom with date type
I am using this code to create my custom style and format. Its for XSSF Format of excel sheet. but it will work for HSSF format with some modification.
XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
defaultFont.FontName = "Arial";
defaultFont.Color = IndexedColors.Black.Index;
defaultFont.IsBold = false;
defaultFont.IsItalic = false;
XSSFCellStyle dateCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat dateDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
dateCellStyle.SetDataFormat(dateDataFormat.GetFormat("m/d/yy h:mm")); //Replace format by m/dd/yyyy. try similar approach for phone number etc.
dateCellStyle.FillBackgroundColor = IndexedColors.LightYellow.Index;
//dateCellStyle.FillPattern = FillPattern.NoFill;
dateCellStyle.FillForegroundColor = IndexedColors.LightTurquoise.Index;
dateCellStyle.FillPattern = FillPattern.SolidForeground;
dateCellStyle.Alignment = HorizontalAlignment.Left;
dateCellStyle.VerticalAlignment = VerticalAlignment.Top;
dateCellStyle.BorderBottom = BorderStyle.Thin;
dateCellStyle.BorderTop = BorderStyle.Thin;
dateCellStyle.BorderLeft = BorderStyle.Thin;
dateCellStyle.BorderRight = BorderStyle.Thin;
dateCellStyle.SetFont(defaultFont);
//Apply your style to column
_sheetData.SetDefaultColumnStyle(columnIndex, dateCellStyle);
// Or you can also apply style cell wise like
var row = _sheetData.CreateRow(0);
for (int cellIndex = 0;cellIndex < TotalHeaderCount;cellIndex++)
{
row.Cells[cellIndex].CellStyle = dateCellStyle;
}

Setting several "setValue" at once

I have some cells (that are non-adjacenet). Each of these has a range name in the form "rLampnn" as below.
ss.getRangeByName("rLamp20").setValue(e.range.getValue());
ss.getRangeByName("rLamp19").setValue(e.range.getValue());
ss.getRangeByName("rLamp18").setValue(e.range.getValue());
I want to put the same value into several of them at once. (Each of them then has a conditional format which changes the cell colour depending on what was entered into them).
Is there a more efficient way (i.e. quicker) of setting the same value into a group of these cells rather than individual calls like above?
If you have many of them you could loop .setValue() using the nn index in the named ranges:
var fName = 'rLamp';
var howManyNamedRanges = 20;
// Assuming the first NamedRange is rLamp0
for (var i=0;i<howManyNamedRanges;i++) {
ss.getRangeByName(fName+i).setValue(e.range.getValue());
}
If the first named ranges is 1 or else you could change it to:
var fName = 'rLamp';
var firstNamedRange = 4;
var lastNamedRange = 20;
// Assuming the first NamedRange is rLamp[n]
for (var i=firstNamedRange;i<=lastNamedRange;i++) {
ss.getRangeByName(fName+i).setValue(e.range.getValue());
}

How to send specific rows of excel to data provider in testNG?

I have created an excel containing multiple rows, each row corresponding to a test case. The Excel has around 22 columns (parameters) including a "Flag" column.
I want the Dataprovider to return only those columns which has a value 'Y' in the excel column. The use case is that when the client wants to run a particular test case, they only need to flag it to Y or N. How can I achieve this is in TestNG with Selenium?
My colleague had helped me to achieve this using following code, but this does not work as per my new code structure.
#DataProvider(name = "Order")
public Object[][] menu()
{
Object[][] data = UtilLibrary.getData("Order");
int intColCount = UtilLibrary.datatable.getColumnCount("Order");
int j = 0;
int arrRowCount=0;
for (int i = 0; i < data.length; i++) {
if((data[i][intColCount-1]).equals("Y"))
{
arrRowCount++;
}
}
j=0;
Object[][] retData = new Object[arrRowCount][intColCount];
for (int i = 0; i < data.length; i++)
{
if ((data[i][intColCount-1]).equals("Y")) {
retData[j] = data[i]; j++; }
}
return retData;
}
The above code sends only the record/s having flag='Y' in the excel to the Dataprovider. But, it was working only when the test script had a single #Test method having all automation steps, while now I have multiple #Test methods to simulate the same steps to which I have passed this same Dataprovider (Order).
Let me know if someone has achieved this using a similar code or if TestNG has a specific feature to send filtered rows of excel to the Dataprovider
I have now fixed the issue. The reason why the above given code for rows having flag = 'Y' in Excel was not working with multiple #Test methods was only due to a silly mistake. The mistake was that I had changed the excel structure a bit and did not modify the above code as per the index of the new flag column.

Autofitting column in combination with setting numberformat will autofit using unformatted text as measurement

When I use EPPlus to autofit a column that is formatted as a date string, the autofit mechanism is using the unformatted string as measurement for how wide the column should become.
Is it a bug or did I do something wrong?
Code
sheet.Column(2).Style.Numberformat.Format = "yyyy-MM-dd hh:mm";
sheet.Cells.AutoFitColumns();
Result:
widening the second column in excel
Autofit using no formatting, notice that the second column is having the same width as the supposed-to-autofit column in the first picture.
For completion, here is the result when no autofit is used
It could be your font settings either in your code or globally in excel. Try running this test (I am posting this as an answer since I cannot fit it in a comment):
[TestMethod]
public void Auto_Col_Fomat_Test()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]
{
new DataColumn("Col1", typeof (int)), new DataColumn("Col2", typeof (DateTime)), new DataColumn("Col3", typeof (object))
});
for (var i = 0; i < 10; i++)
{
var row = datatable.NewRow();
row[0] = i; row[1] = DateTime.Now.AddDays(i); row[2] = Path.GetRandomFileName();
datatable.Rows.Add(row);
}
//Create a test file
var fi = new FileInfo(#"c:\temp\Auto_Col_Fomat.xlsx");
if (fi.Exists)
fi.Delete();
using (var pck = new ExcelPackage(fi))
{
var workbook = pck.Workbook;
var sheet = workbook.Worksheets.Add("Sheet1");
sheet.Cells.LoadFromDataTable(datatable, true);
sheet.Column(2).Style.Numberformat.Format = "yyyy-MM-dd hh:mm";
sheet.Cells.AutoFitColumns();
pck.Save();
}
}
If this shows the same thing you may have changed your default excel font or zoom which means you may have to set the font in code to Body Font size 11 (at least that was 2013 uses). If it doesnt show post more of your code.
I had the same issue.
Here is my work around:
First call AutoFitColumns, then add some padding to the column that has a special format:
cells[sheet.Dimension.Address].AutoFitColumns();
sheet.Column(2).Width *= 1.25;