我想在一个单元格中添加多种样式。
EX:我 需要 一些帮助
现在我一次没有全文。我一次只有一个块(例如,“ I”,“ Want”,“ Some”,“ Help”和相关样式)。但是我需要将整个字符串的格式设置为一个单元格。
如何使用Aspose.cells和Java做到这一点?
您可以为所选字符获取FontSetting对象,然后更改样式。来自Aspose文档的文章参考为http://goo.gl/GhtDDy
API中的EDIT setValue()方法将设置完整值。在您的情况下,您具有与样式关联的块。理想情况下,应该有诸如appendValue(String,Style)之类的方法,但是这种方法在Aspose.Cells库中不存在。请在Aspose论坛中请求此功能。
检查以下方法,您可以使用当前的API来限制样式,仅在方案中应用字体设置。
我假设您有一个字符串数组列表(值块)和一个样式数组列表(每个块的相关样式)。分隔符可以是空格。
public static void main(String[] args) throws Exception
{
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Accessing the added worksheet in the Excel file
Worksheet worksheet = workbook.getWorksheets().get(0);
Cells cells = worksheet.getCells();
ArrayList<String> values = new ArrayList<String>();
ArrayList<Style> styles = new ArrayList<Style>();
// Separator character
String separator = " ";
// I
values.add("I");
styles.add(new Style()); styles.get(0).getFont().setBold(true);
// Want
values.add("Want");
styles.add(new Style()); styles.get(1).getFont().setBold(false);
// Some
values.add("Some");
styles.add(new Style()); styles.get(2).getFont().setBold(true);
// Help
values.add("Help");
styles.add(new Style()); styles.get(3).getFont().setBold(false);
// Get cell A1
Cell cell = cells.get("A1");
appendValuesWithStyles(cell, values, styles, separator);
workbook.save(Common.DATA_DIR + "cellstyle.xlsx");
}
private static void appendValuesWithStyles(Cell cell, ArrayList<String> values, ArrayList<Style> styles, String separator)
{
// Lets combine all chunks, because we can only use setValue()
String allCharacters = "";
// First set the whole value in cell
int iValue = 0;
for (String value : values)
{
allCharacters = allCharacters + value;
if (iValue < values.size())
allCharacters = allCharacters + separator;
iValue++;
}
// Set the value once
cell.setValue(allCharacters);
// Now set the styles
int startIndex = 0, valueLength = 0;
for (int iStyle = 0 ; iStyle < styles.size() ; iStyle++)
{
// Get the associated value and the style.
String value = values.get(iStyle);
Style style = styles.get(iStyle);
// We need the start character and length of string to set the style
valueLength = value.length();
cell.characters(startIndex, valueLength).getFont().setBold(style.getFont().isBold());
// Increment the start index
startIndex = startIndex + valueLength + separator.length();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句