Selected cells CGridCtrl from codeproject - visual-c++

I need to find selected cells for the control CGridCtrl using the following code.
CCellRange cells = m_Grid.GetSelectedCellRange();
if( cells.Count() == 0 )
return ;
for (int i = cells.GetMaxRow(); i >= cells.GetMinRow(); i--)
{
for (int j=cells.GetMinCol(); j<=cells.GetMaxCol();j++)
{
BOOL selected = m_Grid.GetCell(i,j)->IsSelected();
TRACE(_T("Row %d Column %d Selected = %d State %d\n"),i,j,selected, m_Grid.GetCell(i,j)->GetState());
if(selected)
{
m_Grid.DeleteRow(i);
break;
}
}
}
Since the cells I selected are not contiguous, I need to use IsSelected() to find a cell selected. The only last cell return TRUE. Is there a way to determine the cells selected for the control?

I don't know if the flag in the cells are correct, but the correct function to check if a cell is selected are:
BOOL CGridCtrl::IsCellSelected(CCellID &cell) const
BOOL CGridCtrl::IsCellSelected(int nRow, int nCol) const
Just check the implementation. There is a m_SelectedCellMap that contains all selected ranges.

Related

After setting a format and writing some values for a given range, that same format is partially and automatically applied to other ranges

I'm not sure if this is an issue or if it is expected behavior from Excel. If it is indeed expected behavior, I would appreciate an explanation about what is happening, since I cannot see a pattern.
If you set a format and some values to a range and then assign only values to another range located below the first one, the format of the first range is applied partially (randomly?) to the new range.
My test function:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function loadSampleData(applyFormat) {
var columnCount = 30;
if (applyFormat) {
columnCount = 5;
}
var data = [];
for (var rows = 0; rows < 4; rows++) {
var row = [];
for (var columns = 0; columns < columnCount; columns++) {
var value = columns;
if (getRandomInt(1, 3) == 2) {
value = "text";
}
row.push(value);
}
data.push(row);
}
return Excel.run(function (ctx) {
var selectedRange = ctx.workbook.getSelectedRange().load(['rowCount', 'columnCount']);
var extendedRange;
return ctx.sync().then(function () {
var totalRows = data.length;
var totalColumns = data[0].length;
var deltaRows = totalRows - selectedRange.rowCount;
var deltaColumns = totalColumns - selectedRange.columnCount;
extendedRange = selectedRange.getResizedRange(deltaRows, deltaColumns);
if (applyFormat) {
extendedRange.format.fill.color = "orange";
extendedRange.format.font.color = "white";
}
else {
extendedRange.clear();
}
extendedRange.values = data;
}).then(ctx.sync)
}).catch(errorHandler);
}
Steps:
Create one button (Button A) in the task pane. This button must call loadSampleData and pass true, to write some data and format (fill and font color) to a range. (Range A)
Create another button (Button B) in the task pane. This button must call loadSampleData and pass false, to write only data (no format) to a bigger range (Range B).
Click the A1 cell, then click Button A. Notice the range and format that appears.
Click A6, then click Button B. Notice that a bigger range is written and that some of its cells have the same format as the range in step 3, even though no explicit format was set to the range.
With A6 still selected, click Button B multiple times. Notice that as the values of the range change, the formatted cells change as well.
Notes:
This doesn't happen if Range B is written above Range A.
This doesn't happen if Range B is written 4 (or more) rows below Range A.
Thanks!
Fascinatingly, I can reproduce the issue even in the UI, without programmability. Excel is doing some sort of pattern-matching, though I'll admit I have a hard time deciphering what the pattern is...
I will discuss with our team -- but in terms of concrete guidance, I think your safest bet is to set the values, and then clear the formatting. If you want to be super-careful, you can even take it one step further:
Set number formatting (to ensure that strings vs numbers vs date strings get interpreted as you want them to be)
Set the values
range.clear(Excel.ClearApplyTo.formats);
Re-set the number formatting
I will admit that this seems like a workflow worth improving. Let me see if we can either fix "values", or provide a method that lets you set values and number formats in one go, and in a stricter fashion than what is happening today.

How do I get character count from cell

Goal: I'm trying to add a feature to my Excel 2016 VSTO plugin. The feature will get 1 column from the active sheet, and iterate over it changing the background color based on string length.
Problem: I'm having trouble getting string length from the cells. I can not figure out the proper syntax I currently have var count = row.Item[1].Value2.Text.Length;
Code: Here is what I have
public void CharacterLengthCheck(int length = 24, int Column = 3)
{
Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
var RowCount = sheet.UsedRange.Rows.Count;
Range column = sheet.Range[sheet.Cells[1, Column], sheet.Cells[RowCount, Column]];
foreach (Range row in column)
{
var count = row.Item[1].Value2.Text.Length;
if (count > length)
{
row.Item[1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
else
{
row.Item[1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
}
}
}
I think your problem is here:
row.Item[1].Value2.Text.Length
The length function is Len(x), so try Len(row.Item[1].Value2.Text)
Thank you to #Jeeped for their advice on using conditional formatting. However the answer to my original question is.
Change
var count = row.Item[1].Value2.Text.Length;
to
string text = (row.Item[1].Value).ToString();
var count = text.length;
I believe this is because value is dynamic and needs to be explicitly cast to string

How to override PrimeFaces p:dataExporter wrongly exporting numbers as text in Excel?

The PrimeFace p:dataExporter tag exports numeric data as text by default, which results in a cell with a green triangle in the upper left corner. This can be seen in the PrimeFaces showcase example as well, if you click the Excel export under the cars table.
How can I override this default to make sure my numeric columns are not exported as text? I tried using the postProcessor attribute pointing to my method that sets the Excel format for all the data cells using POI API but that did not take effect (did not change anything):
public void formatExcel(Object doc) {
HSSFWorkbook book = (HSSFWorkbook)doc;
HSSFSheet sheet = book.getSheetAt(0);
HSSFRow header = sheet.getRow(0);
int colCount = header.getPhysicalNumberOfCells();
int rowCount = sheet.getPhysicalNumberOfRows();
HSSFCellStyle numStyle = book.createCellStyle();
numStyle.setDataFormat((short)1);
for(int rowInd = 1; rowInd < rowCount; rowInd++) {
HSSFRow row = sheet.getRow(rowInd);
for(int cellInd = 1; cellInd < colCount; cellInd++) {
HSSFCell cell = row.getCell(cellInd);
String val = cell.getStringCellValue();
cell.setCellStyle(numStyle);
}
}
}
I also tried
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
but that gives me
java.lang.IllegalStateException: Cannot get a numeric value from a text cell
So that means that all data is indiscriminately exported as text and then you can't even change it afterwards.
This is what ended up working for me. It is far from elegant but it works:
HSSFCellStyle intStyle = book.createCellStyle();
intStyle.setDataFormat((short)1);
HSSFCellStyle decStyle = book.createCellStyle();
decStyle.setDataFormat((short)2);
HSSFCellStyle dollarStyle = book.createCellStyle();
dollarStyle.setDataFormat((short)5);
for(int rowInd = 1; rowInd < rowCount; rowInd++) {
HSSFRow row = sheet.getRow(rowInd);
for(int cellInd = 1; cellInd < colCount; cellInd++) {
HSSFCell cell = row.getCell(cellInd);
//This is sortof a hack to counter PF exporting all data as text
//We capture the existing value as string, convert to int,
//then format the cell to be numeric and reset the value to be int
String strVal = cell.getStringCellValue();
//this has to be done to temporarily blank out the cell value
//because setting the type to numeric directly will cause
//an IllegalStateException because POI stupidly thinks
//the cell is text because it was exported as such by PF...
cell.setCellType(HSSFCell.CELL_TYPE_BLANK);
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
strVal = strVal.replace(",", StringUtils.EMPTY);
if(strVal.indexOf('.') == -1) {
//integer
//numStyle.setDataFormat((short)1);
int intVal = Integer.valueOf(strVal);
cell.setCellStyle(intStyle);
cell.setCellValue(intVal);
} else {
//double
if(strVal.startsWith("$")) {
strVal = strVal.replace("$", StringUtils.EMPTY);
//numStyle.setDataFormat((short)5);
cell.setCellStyle(dollarStyle);
} else {
//numStyle.setDataFormat((short)2);
cell.setCellStyle(decStyle);
}
double dblVal = Double.valueOf(strVal);
cell.setCellValue(dblVal);
}
}
}
In your postProcessor, you nowhere set the value of the cell to an integer. You set the type, but not the value. Setting the type is not enough. You have to convert value to a number and set it again

How to count cell numbers based on a set of numbers

I am looking for a function which counts how many numbers in a range of cells are in the set of numbers
For example I have the set of numbers(1,2,3) and my cells contains 1 | 2 | 3 | 4 | 5 | 3 , the count should return 4
I have tried using countif but no success, I would like to have an excel function Ex.: =countif(A1:D5,...)
How about this? Assume data is in range A1:D5 and you want to count cells with a value of 1, 2 or 3:
=SUM(COUNTIF(A1:D5, {"1","2","3"}))
I hope my pseudo-code would be understandable
int count(int *set, int set_size, int *cells, int cells_size)
{
int v = 0;
// For every number in set
for(int i = 0; i < set_size; ++i)
{
// Loop through every number in cells
for(int j = 0; j < cells_size; ++j)
{
// If number in cells equals number in set, increment v
if(cells[j] == set[i])
{
v++;
}
}
}
// Result is in v, return it
return v;
}
Of course you can optimize a bit with using better containers than just arrays and sizes of them, but I hope you get the basics from this.
Note I used C-like language for pseudo-code, if anything is unclear I can explain further.

AutoFit Columns Width using jxl library in java [duplicate]

How to autofit content in cell using jxl api?
I know this is an old question at this point, but I was looking for the solution to this and thought I would post it in case someone else needs it.
CellView Auto-Size
I'm not sure why the FAQ doesn't mention this, because it very clearly exists in the docs.
My code looked like the following:
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
c stores the number of columns created
cell is just a temporary place holder for the returned CellView object
sheet is my WriteableSheet object
The Api warns that this is a processor intensive function, so it's probably not ideal for large files. But for a small file like mine (<100 rows) it took no noticeable time.
Hope this helps someone.
The method is self explanatory and commented:
private void sheetAutoFitColumns(WritableSheet sheet) {
for (int i = 0; i < sheet.getColumns(); i++) {
Cell[] cells = sheet.getColumn(i);
int longestStrLen = -1;
if (cells.length == 0)
continue;
/* Find the widest cell in the column. */
for (int j = 0; j < cells.length; j++) {
if ( cells[j].getContents().length() > longestStrLen ) {
String str = cells[j].getContents();
if (str == null || str.isEmpty())
continue;
longestStrLen = str.trim().length();
}
}
/* If not found, skip the column. */
if (longestStrLen == -1)
continue;
/* If wider than the max width, crop width */
if (longestStrLen > 255)
longestStrLen = 255;
CellView cv = sheet.getColumnView(i);
cv.setSize(longestStrLen * 256 + 100); /* Every character is 256 units wide, so scale it. */
sheet.setColumnView(i, cv);
}
}
for(int x=0;x<c;x++)
{
cell=sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
It is fine, instead of scanning all the columns. Pass the column as a parameter.
void display(column)
{
Cell = sheet.getColumnView(column);
cell.setAutosize(true);
sheet.setColumnView(column, cell);
}
So when you wiill be displaying your text you can set the particular length. Can be helpfull for huge excel files.
From the JExcelApi FAQ
How do I do the equivilent of Excel's "Format/Column/Auto Fit Selection"?
There is no API function to do this for you. You'll need to write code that scans the cells in each column, calculates the maximum length, and then calls setColumnView() accordingly. This will get you close to what Excel does but not exactly. Since most fonts have variable width characters, to get the exact same value, you would need to use FontMetrics to calculate the maximum width of each string in the column. No one has posted code on how to do this yet. Feel free to post code to the Yahoo! group or send it directly to the FAQ author's listed at the bottom of this page.
FontMetrics presumably refers to java.awt.FontMetrics. You should be able to work something out with the getLineMetrics(String, Graphics) method I would have though.
CellView's autosize method doesn't work for me all the time. My way of doing this is by programatically set the size(width) of the column based on the highest length of data in the column. Then perform some mathematical operations.
CellView cv = excelSheet.getColumnView(0);
cv.setSize((highest + ((highest/2) + (highest/4))) * 256);
where highest is an int that holds the longest length of data in the column.
setAutosize() method WILL NOT WORK if your cell has over 255 characters. This is related to the Excel 2003 max column width specification: http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP005199291.aspx
You will need to write your own autosize method to handle this case.
Try this exemple:
expandColumns(sheet, 3);
workbook.write();
workbook.close();
private void expandColumn(WritableSheet sheet, int amountOfColumns){
int c = amountOfColumns;
for(int x=0;x<c;x++)
{
CellView cell = sheet.getColumnView(x);
cell.setAutosize(true);
sheet.setColumnView(x, cell);
}
}
Kotlin's implementation
private fun sheetAutoFitColumns(sheet: WritableSheet, columnsIndexesForFit: Array<Int>? = null, startFromRowWithIndex: Int = 0, excludeLastRows : Int = 0) {
for (columnIndex in columnsIndexesForFit?.iterator() ?: IntProgression.fromClosedRange(0, sheet.columns, 1).iterator()) {
val cells = sheet.getColumn(columnIndex)
var longestStrLen = -1
if (cells.isEmpty()) continue
for (j in startFromRowWithIndex until cells.size - excludeLastRows) {
if (cells[j].contents.length > longestStrLen) {
val str = cells[j].contents
if (str == null || str.isEmpty()) continue
longestStrLen = str.trim().length
}
}
if (longestStrLen == -1) continue
val newWidth = if (longestStrLen > 255) 255 else longestStrLen
sheet.setColumnView(columnIndex, newWidth)
}
}
example for use
sheetAutoFitColumns(sheet) // fit all columns by all rows
sheetAutoFitColumns(sheet, arrayOf(0, 3))// fit A and D columns by all rows
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5)// fit A and D columns by rows after 5
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5, 2)// fit A and D columns by rows after 5 and ignore two last rows

Resources