I'm using this Java code to generate Google sheets data from Java application.
List < RowData > rowDataValues = new ArrayList < > ();
List < CellData > headerValues = new ArrayList < > ();
headerValues.add(new CellData().setNote("ID")
.setUserEnteredValue(new ExtendedValue()
.setStringValue("#")).setUserEnteredFormat(myFormat));
.setStringValue("Environment")).setUserEnteredFormat(myFormat));
.........
headerValues.add(new CellData()
.setUserEnteredValue(new ExtendedValue()
.setStringValue("Name")).setUserEnteredFormat(myFormat));
RowData setHeaderValues = new RowData();
setHeaderValues.setValues(headerValues);
rowDataValues.add(setHeaderValues);
requests.add(new Request()
.setUpdateCells(new UpdateCellsRequest()
.setStart(new GridCoordinate()
.setSheetId(randomSheetId)
.setRowIndex(0)
.setColumnIndex(0))
.setRows(rowDataValues)
.setFields("*")));
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
How I can set custom width for each column?
Update:
This is what i've tried so far :
new UpdateDimensionPropertiesRequest().setRange(
new DimensionRange()
.setDimension("COLUMNS")
.setStartIndex(0).setEndIndex(1)
)
.setProperties(new DimensionProperties().setPixelSize(400)).setFields("pixelSize"));
You need to create UpdateDimensionPropertiesRequest. In your case you can use this sample code, which increases the size of first column (startIndex = 0, endIndex = 1) .
requests.add(new Request().setUpdateDimensionProperties(
new UpdateDimensionPropertiesRequest()
.setRange(
new DimensionRange()
.setSheetId(randomSheetId)
.setDimension("COLUMNS")
.setStartIndex(0)
.setEndIndex(1)
)
.setProperties(new DimensionProperties().setPixelSize(400)).setFields("pixelSize"))));
In here i used setDimension("COLUMNS") to change column(s) width, it is possible to change row(s) height by using setDimension("ROWS").
Additional problem from #PeterPenzov 's comment :
I get "Invalid requests.updateDimensionProperties: No grid with id: 0",
You'll get this error when your sheetId is not set properly.
From API v4 documentation SheetId is ;
Individual sheets in a spreadsheet have titles (which must be unique) and IDs. The sheetId is used frequently in the Sheets API to specify which sheet is being read or updated
So you need to set sheetId of DimensionRange Object. In your case you need to use your sheetId as randomSheetId(i've updated the code above).
Spreadsheet spreadsheet = service.spreadsheets().get(spreadsheetId).execute();
spreadsheet.getSheets().stream()
.map(s->s.getProperties().getSheetId())
.forEach(System.out::println);
Please take a look into dev documentation:
{
"requests": [
{
"updateDimensionProperties": {
"range": {
"sheetId": sheetId,
"dimension": "COLUMNS",
"startIndex": 0,
"endIndex": 1
},
"properties": {
"pixelSize": 160
},
"fields": "pixelSize"
}
}
]
}
Request body from the example for column width could be translated into the next Java code:
public void updateFirstColumnWidth(Sheets sheetService, String sheetId) throws IOException {
final Spreadsheet spreadsheet = sheetService.spreadsheets()
.get(sheetId)
.execute();
final var sheets = spreadsheet.getSheets();
final var sheet = sheets.get(0); // get your specific sheet
final int sheetUuid = sheet.getProperties().getSheetId();
final var batchRequest = new BatchUpdateSpreadsheetRequest();
List<Request> requests = List.of(getColumnWidthRequest(sheetUuid, 160));
batchRequest.setRequests(requests);
final BatchUpdateSpreadsheetResponse response = sheetService.spreadsheets()
.batchUpdate(sheetId, batchRequest)
.execute();
}
private Request getColumnWidthRequest(int sheetUuid, int width) {
return new Request()
.setUpdateDimensionProperties(
new UpdateDimensionPropertiesRequest()
.setRange(
new DimensionRange()
.setSheetId(sheetUuid)
.setDimension("COLUMNS")
.setStartIndex(0)
.setEndIndex(1)
)
.setProperties(new DimensionProperties().setPixelSize(width))
.setFields("pixelSize")
);
}
Related
I am trying to implement lazy loading with Grid in Vaadin 8. But it only shows an empty table. What do I do wrong? Also, how do I set the number of items to load (limit) to for example 20 items (the default is 40 items)?
private Grid<Image> makeLazyTable()
{
Grid<Image> grid = new Grid<Image>();
DataProvider<Image, Void> dataProvider = DataProvider.fromCallbacks(
query -> {
int offset = query.getOffset();
int limit = query.getLimit();
OffsetRequest request = new OffsetRequest();
request.setLimit(limit);
request.setOffset(offset);
List<QuerySortOrder> sort = query.getSortOrders();
return ImagesRepository.findAll(request, sort);
},
query -> ImagesRepository.getImageCount()
);
grid.setDataProvider(dataProvider);
return grid;
}
I did not add any columns. That was the reason why the table was empty.
This way it works:
Column<Image, String> filenameColumn = grid.addColumn(Image::getFilename);
Column<Image, String> orientationColumn = grid.addColumn(Image::getOrientation);
Column<Image, String> latitudeColumn = grid.addColumn(Image::getLatitude);
Column<Image, String> longitudeColumn = grid.addColumn(Image::getLongitude);
I am unable to add row to an existing spreadsheet.
I'm trying the steps from here: https://developers.google.com/google-apps/spreadsheets/data
The following line throws the exception below:
row = service.insert(listFeedUrl, row);
Exception:
Exception in thread "main" com.google.gdata.util.InvalidEntryException: Bad Request
Blank rows cannot be written; use delete instead.
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:602)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.insert(Service.java:1409)
at com.google.gdata.client.GoogleService.insert(GoogleService.java:613)
at TestGoogle.main(TestGoogle.java:93)
The full story short: The above example is quite similar with the code in the application that I need to fix, and the application worked some times ago.
I managed to pass the OAuth2 authentication.
The reason you get this error message is probably because you're trying to add to a blank spreadsheet and the header doesn't exist.
If we add the headers first, then it should work.
Using the "Add a list row" example from the documentation you linked; add the headers like this before adding a list row
CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink);
CellFeed cellFeed = service.Query(cellQuery);
CellEntry cellEntry = new CellEntry(1, 1, "firstname");
cellFeed.Insert(cellEntry);
cellEntry = new CellEntry(1, 2, "lastname");
cellFeed.Insert(cellEntry);
cellEntry = new CellEntry(1, 3, "age");
cellFeed.Insert(cellEntry);
cellEntry = new CellEntry(1, 4, "height");
cellFeed.Insert(cellEntry);
Then the list entry example should add to the spreadsheet properly
// Fetch the list feed of the worksheet.
ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
ListFeed listFeed = service.Query(listQuery);
// Create a local representation of the new row.
ListEntry row = new ListEntry();
row.Elements.Add(new ListEntry.Custom() { LocalName = "firstname", Value = "Joe" });
row.Elements.Add(new ListEntry.Custom() { LocalName = "lastname", Value = "Smith" });
row.Elements.Add(new ListEntry.Custom() { LocalName = "age", Value = "26" });
row.Elements.Add(new ListEntry.Custom() { LocalName = "height", Value = "176" });
// Send the new row to the API for insertion.
service.Insert(listFeed, row);
How do I return all timestamped versions of an HBase cell with the Get.setMaxVersions(10) method where 10 is an arbitrary number (could be something else like 20 or 5)? The following is a console main method that creates a table, inserts 10 random integers, and tries to retrieve all of them to print out.
public static void main(String[] args)
throws ZooKeeperConnectionException, MasterNotRunningException, IOException, InterruptedException {
final String HBASE_ZOOKEEPER_QUORUM_IP = "localhost.localdomain"; //set ip in hosts file
final String HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT = "2181";
final String HBASE_MASTER = HBASE_ZOOKEEPER_QUORUM_IP + ":60010";
//identify a data cell with these properties
String tablename = "characters";
String row = "johnsmith";
String family = "capital";
String qualifier = "A";
//config
Configuration config = HBaseConfiguration.create();
config.clear();
config.set("hbase.zookeeper.quorum", HBASE_ZOOKEEPER_QUORUM_IP);
config.set("hbase.zookeeper.property.clientPort", HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT);
config.set("hbase.master", HBASE_MASTER);
//admin
HBaseAdmin hba = new HBaseAdmin(config);
//create a table
HTableDescriptor descriptor = new HTableDescriptor(tablename);
descriptor.addFamily(new HColumnDescriptor(family));
hba.createTable(descriptor);
hba.close();
//get the table
HTable htable = new HTable(config, tablename);
//insert 10 different timestamps into 1 record
for(int i = 0; i < 10; i++) {
String value = Integer.toString(i);
Put put = new Put(Bytes.toBytes(row));
put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier), System.currentTimeMillis(), Bytes.toBytes(value));
htable.put(put);
Thread.sleep(200); //make sure each timestamp is different
}
//get 10 timestamp versions of 1 record
final int MAX_VERSIONS = 10;
Get get = new Get(Bytes.toBytes(row));
get.setMaxVersions(MAX_VERSIONS);
Result result = htable.get(get);
byte[] value = result.getValue(Bytes.toBytes(family), Bytes.toBytes(qualifier)); // returns MAX_VERSIONS quantity of values
String output = Bytes.toString(value);
//show me what you got
System.out.println(output); //prints 9 instead of 0 through 9
}
The output is 9 (because the loop ended at i=9, and I don't see multiple versions in Hue's HBase Browser web UI. What can I do to fix the versions so it gives me 10 individual results for 0 - 9 instead of one result of only the number 9?
You should use getColumnCells on Result to get all versions (depending on MAX_VERSION_COUNT you have set in Get). getValue returns the latest value.
Sample Code:
List<Cell> values = result.getColumnCells(Bytes.toBytes(family), Bytes.toBytes(qualifier));
for ( Cell cell : values )
{
System.out.println( Bytes.toString( CellUtil.cloneValue( cell ) ) );
}
This is a deprecated approach which matches the version of HBase I am currently working on.
List<KeyValue> kvpairs = result.getColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
String line = "";
for(KeyValue kv : kvpairs) {
line += Bytes.toString(kv.getValue()) + "\n";
}
System.out.println(line);
Then, going one step further, it is important to note the setMaxVersions method must be called at table creation to allow for more than a default three values to be inserted into a cell. Here's the updated table creation:
//create a table based on variables from question above
HTableDescriptor tableDescriptor = new HTableDescriptor(tablename);
HColumnDescriptor columnDescriptor = new HColumnDescriptor(columnFamily);
columnDescriptor.setMaxVersions(MAX_VERSIONS);
tableDescriptor.addFamily(columnDescriptor);
hba.createTable(tableDescriptor);
hba.close();
I'm trying to figure out how to parse a JSON feed into a table in Dart. I'm not sure if I should use a Map but if I do, I'm not sure how to approach extracting data. I want to have one cell to hold the assetID, then another for domain name, and another for IP address. Please let me know if you need more information.
Dart:
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
List<String> list = new List<String>();
list.add(jsonString);
for (var x = 0; x < list.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
TableCellElement cell = row.insertCell(x);
cell.text = list.toString();
// print(list);
}
// Iterator itr= list.iterator();
//
// print("Displaying List Elements,");
//
// while(itr.hasNext())
// {
// print(itr.next());
// }
}
JSON
[{"serviceResponseValue":[{"assetId":"8a41250446b89b5f0146b04d49910023","oplock":0,"longitude":115.86,"domainName":"free-aus-trip.au","latitude":-31.95,"ipAddress":"6.0.0.6"},{"assetId":"8a49859246918966014691b1aac9000c","oplock":0,"longitude":-65.30,"domainName":null,"latitude":-24.18,"ipAddress":"4.0.0.4"},{"assetId":"8a49859246876566014691b1437512e4","oplock":0,"longitude":77.60,"domainName":"allmovies.cn","latitude":12.97,"ipAddress":"14.0.0.14"},{"assetId":"8a49850446b04b5f0146b04d49910000","oplock":0,"longitude":112.47,"domainName":"getrichez.cn","latitude":32.98,"ipAddress":"5.0.0.5"},{"assetId":"8a498592469189660146919b7a210006","oplock":0,"longitude":-37.61,"domainName":"googles.com","latitude":55.75,"ipAddress":null},{"assetId":"8a42250876b89b5f0876b04d49910763","oplock":0,"longitude":-68.90,"domainName":"lolcatzfun.net","latitude":-22.48,"ipAddress":"8.0.0.8"},{"assetId":"8a498592469189660146919f8d700008","oplock":0,"longitude":113.50,"domainName":"ccn.com","latitude":52.03,"ipAddress":null},{"assetId":"8a45250446b89b5f0876b04d49910187","oplock":0,"longitude":115.84,"domainName":"free-aus-trip.au","latitude":-31.86,"ipAddress":"7.0.0.7"},{"assetId":"8a49859246918966014691aeda76000a","oplock":0,"longitude":3.38,"domainName":"cashnow.net","latitude":6.52,"ipAddress":"2.0.0.2"},{"assetId":"8a49859246918966014691ae19df0009","oplock":0,"longitude":7.48,"domainName":"free-money.tv","latitude":9.07,"ipAddress":"222.222.222.222"},{"assetId":"8a498592469189660146919e09900007","oplock":0,"longitude":30.34,"domainName":"facebok.com","latitude":59.93,"ipAddress":"111.111.111.222"},{"assetId":"8a49859246918966014691b14375000b","oplock":0,"longitude":116.41,"domainName":null,"latitude":39.90,"ipAddress":"0.0.0.111"}],"messages":{"messages":[]}}]
To work with JSON, you have in dart a great thing : dart:convert => JSON
here some example of use:
var encoded = JSON.encode([1, 2, { "a": null }]);
var decoded = JSON.decode('["foo", { "bar": 499 }]');
I have done some thing but i'm not sure that is fit perfectly with your need
import 'dart:html';
import 'dart:convert';
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
var jsonObject = JSON.decode(jsonString);
for (var x = 0; x < jsonObject.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
for (var d in jsonObject[x]["serviceResponseValue"]) {
TableCellElement cell = row.insertCell(x);
cell.text = d["assetId"];
cell = row.insertCell(x);
cell.text = d["domainName"];
cell = row.insertCell(x);
cell.text = d["ipAddress"];
print(d["assetId"]);
print(d["domainName"]);
print(d["ipAddress"]);
}
// print(list);
}
}
You parse JSON into a Dart data structure using
import 'dart:convert' show JSON;
var decoded = JSON.decode(jsonString);
see also How to handle JSON in Dart (Alexandres answer)
decoded is then a Dart data structure (lists, maps, values) that you can iterate over or investigate in the debugger. If you need further assistance please add a comment.
I have this formula, which successfully lists all of my files in a folder. Awesome. But, can I also, within this script list some specific cell data from each file?
function listFilesInFolder() {
var folder = DocsList.getFolder("1- Summaries");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", "Download", "Description", "Type"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
if (file.getFileType() == "SPREADSHEET") {
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getValue(B10), **(THIS IS WHERE I WOULD LIKE TO GET DATA, but it does not work)**
file.getUrl(),
"https://docs.google.com/a/acme.com/spreadsheet/ccc?key=" + file.getId(),
file.getDescription(),
"audio/mp3"
]
sheet.appendRow(data);
You can read from the spreadsheet, yes.
In the place where if (file.getFileType()... is, put this:
var cellValue;
if (file.getFileType() === "SPREADSHEET") {
cellValue = SpreadsheetApp.openById(file.getId()).getSheetByName("NameOfSheet")
.getRange("B10").getValue();
} else {
cellValue = null; // specify some default value here!
}
...
Then in your data array:
data = [
file.getName(),
file.getDateCreated(),
cellValue,
...