POI - unable to create custom validation for a range of cells - constraints

I need to check if the user has entered a valid number in a cells A1:A10. In Excel i would choose the cells and then create a custom validator and set the formula to =isNumber("$A$1:$A10")
Trying do this using POI is getting me all tied in knots:
Here is what i have tried:
CellRangeAddressList addressList = new CellRangeAddressList(0, 10, 0, 0);
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
DataValidationConstraint customConstraint = dvHelper.createCustomConstraint("isNumber(\"$A$0:$A$10\"");
XSSFDataValidation validation = (XSSFDataValidation)dvHelper.createValidation(customConstraint, addressList);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
When i try and open this in Excel, i get an error and Excel disables the validation
thanks in advance
-anish

CellReference crStartCell = new CellReference(startRow, column, true, true); // 0-based row and column index
CellReference crEndCell = new CellReference(endRow, column, true, true);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createCustomConstraint("ISNUMBER("+crStartCell.formatAsString()+":"+crEndCell.formatAsString() +")");

You can convert that excel to csv than perform your validations using SuperCSV. It would be length but more easier.

Related

Creating a C# List collection equivalent VBscript two dimensional array

VBscript:
arytwoDim(1,intLastBucketBlockIndex) = "08:30 AM" 'TIME
arytwoDim(2,intLastBucketBlockIndex) = 5 'Resource QTY
I would like to create a List collection equivalent to vb array, so that I can mirror the logic with hard coded row,cols.
I tried loading list like this:
List<List<String>> arytwoDim = new List<List<String>>(); //Creates new nested List
arytwoDim .Add(new List<String>()); //Adds new sub List
arytwoDim [1][intLastBucketBlockIndex] = "08:30 AM"; //TIME
arytwoDim [2][intLastBucketBlockIndex] = 5; //Resource QTY
I received this error: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
I confirmed that value intLastBucketBlockIndex contains is 0.
Please advise, thank you in advance for your help!

How to add field to a Shapefile using DotSpatial?

I tried searching the web to find a sample of showing how to add a Field to attribute table of an existing shapefile. For example I have a Shapefile at
C://data/Streets.shp
and need to add two field L_CITY and R_CITY both text and 50 characters limit. How can I do this in DotSpatial?
The first thing you need to do is add a reference to System.Data. Otherwise, the type definition for the DataTable is not available and it may not be obvious what you can do to modify the schema.
Then you can use standard DataTable programming like the following code:
public void AddFieldExample()
{
IFeatureSet fs = FeatureSet.OpenFile("C:\\YourShapefile.shp");
DataTable table = fs.DataTable;
DataColumn lCity = table.Columns.Add("L_CITY");
lCity.MaxLength = 50;
DataColumn rCity = table.Columns.Add("R_CITY");
rCity.MaxLength = 50;
}

Dynamics AX : error while importing data from excel on client

I did a custom X++ code to import data from Excel to General Ledger, however the import works very well on the server directly but while running it from the end user(client) it imports several records (like 24 records) then throw an error
the number of argument provided is different from the number of argument provided to the method
it is obvious that the error is related to connectivity issue since I have tried the same Excel file on the on the server and successfully imported.
in order to prevent this issue I was thinking to alternative solution rather than looping the through the excel file and do the business and insert the records, instead I thought it might be useful if I save the file directly/ bulk save in a table or something else then try to loop through the table to prevent the connectivity issue.
note: several solution are available on google such as windows ghosting but none works for me
could anyone please advise about that or suggest the suitable solution
I would recommend you save the Excel file as tab-separated text, then do the import using the TextIO class.
You will also benefit from a +10 times increase in performance!
static void ExcelTest(Args _args)
{
#Excel
FilePath excelFile = #'C:\Users\user\Documents\MyExcelFile.xlsx';
FilePath textFile = #'C:\Users\user\Documents\MyTextFile.txt';
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbooks workBooks = application.get_Workbooks();
Microsoft.Office.Interop.Excel.Workbook workBook;
// Save the excel file as tab-separated text
application.set_DisplayAlerts(false);
application.set_Visible(false);
new FileIOPermission(excelFile, 'r').assert();
workBooks.Open(excelFile, 0, true, 5, '', '', true, #xlWindows, '', false, false, 1, false, false, 1);
CodeAccessPermission::revertAssert();
workBook = workBooks.get_Item(1);
new FileIOPermission(textFile, 'w').assert();
CodeAccessPermission::revertAssert();
workBook.SaveAs(textFile, #xlTextWindows, '', '', false, false, null, #xlLocalSessionChanges, false, null, null, false);
workBooks.Close();
application.Quit();
// Now read the text file
new FileIOPermission(textFile, 'r').assert();
io = new TextIo(textFile, 'r');
if (!io)
throw error("#SYS18447");
io.inFieldDelimiter('\t');
for (con = io.read(); io.status() == IO_Status::Ok; con = io.read())
{
info(con2str(con));
}
}

Merging rows into single using spreadsheet gear while exporting to Excel

I have to merge the rows of excel using spreadsheet gear controls is it possible. Only specific rows of single column
All detail is being included in this screencast
The changes that has been done by me is
DataTable dt = (DataTable)ViewState["dtGrid"]
System.Random rd = new System.Random(DateTime.Now.Millisecond);
int MyValue = rd.Next(1000000, 99999999);
sUniqueName = MyValue.ToString();
// Create a new workbook.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IRange cells = workbook.Worksheets[0].Cells;
cells.CopyFromDataTable(dt, SpreadsheetGear.Data.SetDataFlags.None);
cells.Rows[0, 0, 0, 51].Interior.Color = System.Drawing.Color.Navy;
cells.Rows[0, 0, 0, 51].Font.Color = System.Drawing.Color.White;
cells["A:R"].Columns.AutoFit();
string filename = string.Format("{0}-{1}-{2}", "AOMIndoorInventoryReport", DateTime.Now.ToString("MM-dd-yy"), sUniqueName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".xls");
workbook.SaveToStream(Response.OutputStream, SpreadsheetGear.FileFormat.Excel8);
Response.End();
What should be added?
You can merge cells by calling IRange.Merge() on the desired cells. Example:
cells["A7:A8"].Merge();
cells[8, 0, 22, 0].Merge();
UPDATE:
You've asked how to dynamically merge a range of cells based on adjacent rows in a column which have the same value. To accomplish this would require looping through each row in this column and comparing each cell's value with the previous value, merging when appropriate as you go down the column.
I am providing some sample code below which demonstrates one way in which you might go about this (there are certainly many other ways). I had to make some assumptions about your underlying data and requirements, so some modification on your end might be needed. Note the use of some handy methods under the IRange interface (see the IRange.Intersect(...) / Subtract(...) / Union(...) methods) which allow you to "interact" two IRanges to create a new third IRange.
...
// Create a new workbook and some local variables for convenience.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[0];
SpreadsheetGear.IRange cells = worksheet.Cells;
// Copy data from DataTable to worksheet
cells.CopyFromDataTable(dt, SpreadsheetGear.Data.SetDataFlags.None);
// Here I am creating an IRange representing the used part of column a and without
// the header row, which I presume is in Row 1, and should not be included in this
// merging routine.
SpreadsheetGear.IRange usedColA = worksheet.UsedRange.Intersect(
cells["A:A"]).Subtract(cells["1:1"]);
// No point in attempting to merge cells if there's only a single row.
if (usedColA.RowCount > 1)
{
// Some variables to keep track of the content of the "current" and "previous"
// cells as we loop through "usedColA".
string prevCellVal = "";
string curCellVal = "";
// We'll use this variable to keep track of ranges which will need to be merged
// during the routine. Here I seed "mergeRange" with the first cell in usedColA.
SpreadsheetGear.IRange mergeRange = usedColA[0, 0];
// Loop through each cell in the used part of Column A.
foreach (SpreadsheetGear.IRange cell in usedColA)
{
// Get text of current "cell".
curCellVal = cell.Text;
// Your screenshot seems to indicate that you don't care about merging empty
// cells so this routine takes this into account. Either an empty cell or
// mismatched text from the "current" and "previous" cell indicate we should
// merge whatever cells we've accumulated in "mergeRange" and then reset this
// range to look for more ranges to merge further down the column.
if (curCellVal.Length == 0 || curCellVal != prevCellVal)
{
// Only merge if this range consists of more than 1 cell.
if (mergeRange.CellCount > 1)
mergeRange.Merge();
// Reset merged range to the "current" cell.
mergeRange = cell;
prevCellVal = curCellVal;
}
// If the current and previous cells contain the same text, add this "cell"
// to the "mergeRange". Note the use of IRange.Union(...) to combine two
// IRange objects into one.
else if (curCellVal == prevCellVal)
mergeRange = mergeRange.Union(cell);
}
// One last check for any cells to merge at the very end of the column.
if (mergeRange.CellCount > 1)
mergeRange.Merge();
}
...

How to Advance filter for category and author in Smartsearch in kentico

I have created basic search and uses the SearchHelper to get smart search results based on the search paramaters.
Now creating the Advance search based on Category , Author etc but did not find the way to filter the result based on these condition.
I am looking for a way to display the results using the dataset that
// Prepare parameters
SearchParameters parameters = new SearchParameters()
{
SearchFor = searchText,
SearchSort = SearchHelper.GetSort(srt),
Path = path,
ClassNames = DocumentTypes,
CurrentCulture = culture,
DefaultCulture = defaultCulture,
CombineWithDefaultCulture = CombineWithDefaultCulture,
CheckPermissions = CheckPermissions,
SearchInAttachments = SearchInAttachments,
User = (UserInfo)CMSContext.CurrentUser,
SearchIndexes = Indexes,
StartingPosition = startPosition,
DisplayResults = displayResults,
NumberOfProcessedResults = numberOfProceeded,
NumberOfResults = 0,
AttachmentWhere = AttachmentsWhere,
AttachmentOrderBy = AttachmentsOrderBy,
BlockFieldOnlySearch = BlockFieldOnlySearch,
};
// Search
DataSet results = SearchHelper.Search(parameters);
The easiest way is to use the method:
SearchHelper.CombineSearchCondition()
The first parameter is the searchText, with the search terms you probably already have.
The second parameter is searchConditions, which can be formatted as per https://docs.kentico.com/k10/configuring-kentico/setting-up-search-on-your-website/smart-search-syntax
Alternatively you could just append your search conditions to your search text manually, separating each term with a space.
Remember that to filter based on any field they need to be selected as searchable in the SiteManager->Development->DocumentTypes->DocumentType->Search Tab.

Resources