2016-12-30 33 views
11

我想设置电子表格单元格背景颜色和文本大小。我使用这个Java代码将文本设置到单元格中,但我找不到如何设置样式的解决方案。使用Google Java API设置单元格背景颜色和文本大小

CellData setUserEnteredValue = new CellData() 
      .setUserEnteredValue(new ExtendedValue() 
       .setStringValue("cell text")); 

有没有解决方法?

+0

不知道如果这个工程在Java中,但你可以尝试的方法[的setBackground(颜色)](https://开头developers.google.com/apps-script/reference/spreadsheet/range#setbackgroundcolor),或者您可以使用[http请求](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets #cellformat) –

+0

你能告诉我代码示例吗? –

回答

4

AFAIK这在Java Spreadsheet API中是不可能的,您必须使用Apps脚本; https://developers.google.com/apps-script/reference/spreadsheet/

从他们的文档中,how to set the background;

var ss = SpreadsheetApp.getActiveSpreadsheet(); 
var sheet = ss.getSheets()[0]; 

var range = sheet.getRange("B2:D5"); 
range.setBackground("red"); 

and how to set the font size;

var ss = SpreadsheetApp.getActiveSpreadsheet(); 
var sheet = ss.getSheets()[0]; 

var cell = sheet.getRange("B2"); 
cell.setFontSize(20); 

更新 See flo5783's answer below,现在V4提供了这样做的能力。

0

您无法更改CellData对象上的背景颜色或字体大小。你需要迭代一些单元格范围。从那里,您可以根据单元格值设置背景颜色。然后你可以使你的代码可靠,就像一个两步过程。 从上SO另一个答案:

//Sets the row color depending on the value in the "Status" column. 
function setRowColors() { 
    var range = SpreadsheetApp.getActiveSheet().getDataRange(); 
    var statusColumnOffset = getStatusColumnOffset(); 

    for (var i = range.getRow(); i < range.getLastRow(); i++) { 
    rowRange = range.offset(i, 0, 1); //Play with this range to get your desired columns. 
    status = rowRange.offset(0, statusColumnOffset).getValue(); //The text value we need to evaluate. 
    if (status == 'Completed') { 
     rowRange.setBackgroundColor("#99CC99"); 
    } else if (status == 'In Progress') { 
     rowRange.setBackgroundColor("#FFDD88");  
    } else if (status == 'Not Started') { 
     rowRange.setBackgroundColor("#CC6666");   
    } 
    } 
} 
+0

请问您可以向我展示Java v4 API的示例吗? –

+0

只是要清楚。你是否在寻找这样的东西:https://developers.google.com/sheets/api/samples/conditional-formatting ?? –

+0

是的,我想用Java API v4制作相同的结果 –

2

貌似正好有专为这个类: CellFormat

特别是以下这些方法:

public CellFormat setBackgroundColor(ColorbackgroundColor)

public CellFormat setTextFormat(TextFormattextFormat)

我没有用Java编码的年龄,所以我不会尝试给你一个工作代码示例,但我认为你可以从这个容易弄明白。

编辑:下面是你的代码开始一个基本的例子:

CellData setUserEnteredValue = new CellData() 
      .setUserEnteredValue(new ExtendedValue() 
       .setStringValue("cell text")); 

CellFormat myFormat = new CellFormat(); 
myFormat.setBackgroundColor(new Color().setRed(1)); // red background 
myFormat.setTextFormat(new TextFormat().setFontSize(16)); // 16pt font 

setUserEnteredValue.setUserEnteredFormat(myFormat); 
+0

我刚刚在**编辑**下面添加了一个,使用我最初提到的javadoc链接。 – flo5783

+0

请用setUserEnteredFormat更新答案。 setEffectiveFormat不起作用。 –

+1

@PeterPenzov让我知道这是否有效,如果是的话,我会用“读下来”来更新我的答案。 – JayIsTooCommon

相关问题