I have below loop trying to printout keys and values stored in a hashmap
// Create the first row corresponding to the header
Row header = Sheet.createRow(0);
int headerIndex = 0;
for (Map.Entry<String, List<String>> entry : resultsToPrint.entrySet()) {
String key = entry.getKey();
header.createCell(headerIndex).setCellValue(key);
int rowIndex = 1;
for (String value : entry.getValue()) {
// Creating row
Row row = Sheet.createRow(rowIndex);
// create cell
row.createCell(headerIndex).setCellValue(value);
rowIndex++;
}
headerIndex++;
}
the results I am getting looks like this:
This is what gets printed
what I need this loop to do, is to populate the values of the second column as well and if I add a third column, it needs to populate the values for the third column etc.
Please assist
Related
I have been looking endlessly for a method to compare values on different columns in the same row, to know which cell I should update.
The speradsheet is a simple model of stock management (it's quite simple and I've been doing it manually), but I wanted a 'faster'(*) ou automated way of updating the amounts os each item, and the timestamps (which are two: one for adding units to the stock, and one for withdrawing).
The obstacles so far are:
The onEdit() function won't work on automated changes like macros, so it's off the table;
I need to scan the whole spreadsheet to find every filled cell on column D, which carries the value i'm adding to or subtracting from my column C;
-For this i have already setup do filter the column 'from Z to A' to get all the cells with values on them, but the amount of items changed can vary, so i cant set a search with a fixed number of rows.
Since my sheet has over 90 entries (likely to increase) of at least 6 columns each, a for loop with if statements takes too long, (*)but execution time is not exactly the main concern right now.
The code is as follows, and I'll be attaching a picture of the sheet I'm working with.
/** #OnlyCurrentDoc */
function geral() {
filtro();
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('G2').activate();
spreadsheet.getCurrentCell().setFormula('=C2+D2');
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('G2:G92'), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
var currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
currentCell.activateAsCurrentCell();
spreadsheet.getRange('C2').activate();
spreadsheet.getRange('G2:G').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
spreadsheet.getRange('G:G').activate();
spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
//adds the input OR output timestamp depending on the value in D column
//!!WORK IN PROGRESS!! --> here's where it gets tricky, and that's what I got so far (which doesn't work)
/*
for (var i = 2; i < 100; i++) {
spreadsheet.getRange('J2').setValue("TESTE");
var cell1 = spreadsheet.getRange('????').getValue(); //from this point on, I don't know how to proceed
var cell2 = spreadsheet.getRange('????').getValue();
spreadsheet.getRange('J2').setValue("TESTE2");
if(cell1 > cell2){
spreadsheet.getRange('????').activate();
spreadsheet.getActiveCell().setValue(new Date());
}
else if(cell1 < cell2){
spreadsheet.getRange('????').activate();
spreadsheet.getActiveCell().setValue(new Date());
}
}
*/
spreadsheet.getRange('D2:D').activate();
spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
};
function filtro() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('D:D').activate();
spreadsheet.getActiveSheet().sort(4, false);
};
EDIT: With my review after #IrvingJayG.'s comment, I noticed a few mistakes and unnecessary extra steps, so instead of doing all the copy-paste-delete dance and then compare results, I'd go for the pseudocode below:
//Ci's value pre-exists in the sheet, where i is the row index
//manually input Di value
//set formula for Gi = Ci+Di
//and then compare either Ci and Gi, or Di and 0
if(Di > 0){
//the following steps can be defined as a new function for each case, (e.g. updateIn() and updateOut())
copy Gi to Ci;
update Ei with new Date();
delete Gi and Di;
}
else if(Di < 0){
copy Gi to Ci;
update Fi with new Date();
delete Gi and Di;
}
Unfortunately, it still doesn't solve my problem, just simplifies the code by a lot.
Sheet example
RECOMMENDATION:
I've created a sample sheet (based on your attached example sheet) with 6 rows of data and with 4 random sample cell values on Column D. Then, I've created a sample script below, where you can use a reference:
NOTE: This script will scan every row on your sheet that has data (e.g. if you have 30 rows of data, it will scan every row one-by-one until it reaches the 30th row) and may slow-down once you have bunch of data on it. That's the catch because it's an expected behavior
SAMPLE SHEET:
SCRIPT:
function onOpen() { //[OPTIONAL] Created a custom menu "Timestamp" on your Spreadsheet, where you can run the script
var ui = SpreadsheetApp.getUi();
ui.createMenu('Timestamp')
.addItem('Automate Timestamp', 'mainFunction')
.addToUi();
}
function mainFunction() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('D:D').activate();
spreadsheet.getActiveSheet().sort(4, false);
automateSheetCheck();
}
function automateSheetCheck(){
var d = new Date();
var formattedDate = Utilities.formatDate(d, "GMT", "MM/dd/yyyy HH:mm:ss");
var spreadsheet = SpreadsheetApp.getActive();
var currentRow = spreadsheet.getDataRange().getLastRow(); //Get the last row with value on your sheet data as a whole to only scan rows with values
for(var x =2; x<=currentRow; x++){ //Loop starts at row 2
if(spreadsheet.getRange("D"+x).getValue() == ""){ //Checks if D (row# or x) value is null
Logger.log("Cell D"+x+" is empty"); //Logs the result for review
}else{
var res = spreadsheet.getRange("C"+x).getValue() + spreadsheet.getRange("D"+x).getValue(); //SUM of C & D values
if(spreadsheet.getRange("D"+x).getValue() > 0){ // If D value is greater than 0, E cell is updated with new timestamp and then C value is replaced with res
Logger.log("Updated Timestamp on cell E"+x + " because D"+x+ " with value of "+ spreadsheet.getRange("D"+x).getValue() +" is greater than 0"); //Logs the result for review
spreadsheet.getRange("E"+x).setValue(formattedDate);
spreadsheet.getRange("C"+x).setValue(res); //Replace C value with "res"
spreadsheet.getRange("D"+x).setValue(""); //remove D value
}else{ // If D value is less than 0, F cell is updated with a new timestamp
Logger.log("Updated Timestamp on cell F"+x + " because D"+x+ " with value of "+ spreadsheet.getRange("D"+x).getValue() +" is less than 0"); //Logs the result for review
spreadsheet.getRange("F"+x).setValue(formattedDate);
spreadsheet.getRange("C"+x).setValue(res); //Replace C value with "res"
spreadsheet.getRange("D"+x).setValue(""); //remove D value
}
}
}
}
RESULT:
After running the script, the will be the result on the sample sheet:
Here's the Execution Logs, where that you can review what happened after running the code:
I want to click on an exact row in a WinTable where my criteria meets but couldnt succeed so far. I can search criteria for an exact row but I can not get total number of rows so that I would make a loop for all rows. I tried collection and table.Rows.Count,but both brings nothing to me. Can someone help me on this ?
#region Variable Declarations
WinTable uIG1Table = this.UIProMANAGEWindow.UIDefinitionsWindow.UIG1Window.UIG1Table;
WinRow dataGridrow = uIG1Table.GetRow(0);
#endregion
UITestControlCollection rows = uIG1Table.Rows;
// MessageBox.Show(rows[5].RowIndex.ToString());
foreach (WinRow row in uIG1Table.Rows)
{
foreach (WinCell cell in row.Cells)
{
if (cell.Value.ToString() == "E81")
Mouse.Click(cell, new Point(5, 0));
}
}
and this is the code with for loop
int rows = uIG1Table.Rows.Count;
for (int i = 0; i < rows; i++)
{
foreach (WinCell cell in dataGridrow.Cells)
{
if (cell.Value.ToString() == "E81")
Mouse.Click(cell, new Point(5, 0));
}
}
When doing a GetChildren() on a row, you will notice that the first child is of type RowHeader. A user typically clicks the row header to select the row.
Following code will iterate all the rows in a DataGridView and click the row header, effectively selecting the row:
UITestControlCollection rows = YourUIMapTable.Rows;
foreach (UITestControl row in rows)
{
UITestControl rowHeader = row.GetChildren().Single(child => child.ControlType == ControlType.RowHeader);
Mouse.Click(rowHeader);
}
If you want to select a specific row, you can do something like this:
Mouse.Click(YourUIMapTable.Rows[putIndexNumberHere].GetChildren().Single(child => child.ControlType == ControlType.RowHeader));
The sample code above is based on the program I wrote in my answer to this question:
How to get cell color information of a WinCell with codedui?
I want to get row and colun numbers for a table but can not do it.
here is my table
WinTable uIG1Table = this.UIProMANAGEWindow.UIMachineListWindow.UIG1Window.UIG1Table;
First I used methods I have seen in this link but it did not work
http://executeautomation.com/blog/storetableinlist/
int rowCount = uIG1Table.RowCount;
int colCount = uIG1Table.ColumnCount;
I searched for WinTable API and I tried to use API methods. Since there is no columng structures, I used ColumnHeaders for column counting , both row and column brings me 0. Whata should I do ?
int rowCount = uIG1Table.Rows.Count;
int colCount = uIG1Table.ColumnHeaders.Count;
MessageBox.Show(rowCount.ToString());
MessageBox.Show(colCount.ToString());
Try searching all rows on the window using following code example:
internal UITestControlCollection GetGridRows()
{
var winSearchResults = FindWindowSearchResults();// this can be any WinWindow object
WinRow gridRows = new WinRow(winSearchResults);
gridRows.SearchProperties.Add(WinRow.PropertyNames.Name, "Row ", PropertyExpressionOperator.Contains);// in case of my AUT, the rows name property had "Row " at start
gridRows.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
return gridRows.FindMatchingControls();
}
Once you have a row object, you can get cell count through cells property as below:
rowFromGrid.Cells
I have a spreadsheet with 2 tabbed sheets. I am trying to run a macro so that when the user inputs a name in B2 of the 2nd sheet, it is matched with every instance of that name in the 1st sheet, column B. I then need to copy all of the data that appears in the matched cell's rows and have that pasted in the 2nd sheet starting with cell B3.
I have limited experience with VBA, but none with JS/Google-apps-script. Any help with how to write this would be greatly appreciated! Here is my first shot:
function onSearch() {
// raw data sheet
var original = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 2");
// search for student sheet
var filtered = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Student Progress Search");
// retrieving the values in the raw data array of names
var searchColumn = 2;
var lr = original.getLastRow();
var searchRange = original.getRange(2,searchColumn, lr, 1).getValues();
// retrieving the name submitted on search
var inputName = filtered.getRange(2, 2).getValue();
// loop through all the names in the raw data and identify any matches to the search name
for (var i = 0; i < lr; i++){
var dataValue = searchRange[i];
var r = dataValue.getRow();
var line = [[r]];
var paste = filtered.getRange(3, 3);
// if the data is a match, return the value of that cell in the searched sheet
if (dataValue == inputName){ return paste.setValues(line);
}
}
}
Not sure if the built-in QUERY function would work for you. This here does exactly what you are looking for:
=QUERY(Sheet1!B:B,"select B where LOWER(B) like LOWER('%" &B2& "%')")
For example, if a user enters 'joe', the function will match any entry containing 'joe', regardless of case.
I am using openxml to create an excel report. The openxml operates on a template excel file using named ranges.
The client requires a totals row at the end of the list of rows. Sounds like a reasonable request!!
However, the data table I'm returning from the db can contain any number of rows. Using template rows and 'InsertBeforeSelf', my totals row is getting overridden.
My question is, using openxml, how can I insert rows into the spreadsheet, causing the totals row to be be moved down each time a row is inserted?
Regards ...
Assuming you're using the SDK 2.0, I did something similiar by using this function:
private static Row CreateRow(Row refRow, SheetData sheetData)
{
uint rowIndex = refRow.RowIndex.Value;
uint newRowIndex;
var newRow = (Row)refRow.Clone();
/*IEnumerable<Row> rows = sheetData.Descendants<Row>().Where(r => r.RowIndex.Value >= rowIndex);
foreach (Row row in rows)
{
newRowIndex = System.Convert.ToUInt32(row.RowIndex.Value + 1);
foreach (Cell cell in row.Elements<Cell>())
{
string cellReference = cell.CellReference.Value;
cell.CellReference = new StringValue(cellReference.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString()));
}
row.RowIndex = new UInt32Value(newRowIndex);
}*/
sheetData.InsertBefore(newRow, refRow);
return newRow;
}
I'm not sure how you were doing it with InsertBeforeSelf before, so maybe this isn't much of an improvement, but this has worked for me. I was thinking you could just use your totals row as the reference row. (The commented out part is for if you had rows after your reference row that you wanted to maintain. I made some modifications, but it mostly comes from this thread: http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/65c9ca1c-25d4-482d-8eb3-91a3512bb0ac)
Since it returns the new row, you can use that object then to edit the cell values with the data from the database. I hope this is at least somewhat helpful to anyone trying to do this...
[Can someone with more points please put this text as a comment for the M_R_H's Answer.]
The solution that M_R_H gave helped me, but introduces a new bug to the problem. If you use the given CreateRow method as-is, if any of the rows being moved/re-referenced have formulas the CalcChain.xml (in the package) will be broken.
I added the following code to the proposed CreateRow solution. It still doesn't fix the problem, because, I think this code is only fixing the currently-being-copied row reference:
if (cell.CellFormula != null) {
string cellFormula = cell.CellFormula.Text;
cell.CellFormula = new CellFormula(cellFormula.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString()));
}
What is the proper way to fix/update CalcChain.xml?
PS: SheetData can be gotten from your worksheet as:
worksheet.GetFirstChild<SheetData>();
You have to loop all rows and cells under the inserted row,change its rowindex and cellreference. I guess OpenXml not so smart that help you change index automatically.
static void InsertRow(string sheetName, WorkbookPart wbPart, uint rowIndex)
{
Sheet sheet = wbPart.Workbook.Descendants<Sheet>().Where((s) => s.Name == sheetName).FirstOrDefault();
if (sheet != null)
{
Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(sheet.Id))).Worksheet;
SheetData sheetData = ws.WorksheetPart.Worksheet.GetFirstChild<SheetData>();
Row refRow = GetRow(sheetData, rowIndex);
++rowIndex;
Cell cell1 = new Cell() { CellReference = "A" + rowIndex };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "";
cell1.Append(cellValue1);
Row newRow = new Row()
{
RowIndex = rowIndex
};
newRow.Append(cell1);
for (int i = (int)rowIndex; i <= sheetData.Elements<Row>().Count(); i++)
{
var row = sheetData.Elements<Row>().Where(r => r.RowIndex.Value == i).FirstOrDefault();
row.RowIndex++;
foreach (Cell c in row.Elements<Cell>())
{
string refer = c.CellReference.Value;
int num = Convert.ToInt32(Regex.Replace(refer, #"[^\d]*", ""));
num++;
string letters = Regex.Replace(refer, #"[^A-Z]*", "");
c.CellReference.Value = letters + num;
}
}
sheetData.InsertAfter(newRow, refRow);
//ws.Save();
}
}
static Row GetRow(SheetData wsData, UInt32 rowIndex)
{
var row = wsData.Elements<Row>().
Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault();
if (row == null)
{
row = new Row();
row.RowIndex = rowIndex;
wsData.Append(row);
}
return row;
}
Above solution got from:How to insert the row in exisiting template in open xml. There is a clear explanation might help you a lot.