import java.io.FileOutputStream;\r
\r
/**\r
- * Demonstrates various alignment options\r
+ * Shows how various alignment options work.\r
*/\r
public class AligningCells {\r
\r
- public static void main(String[] args)\r
- throws Exception\r
- {\r
- Workbook wb = new XSSFWorkbook();\r
+ public static void main(String[] args) throws Exception {\r
+ Workbook wb = new XSSFWorkbook();\r
\r
- Sheet sheet = wb.createSheet("new sheet");\r
- Row row = sheet.createRow((short) 2);\r
+ Sheet sheet = wb.createSheet();\r
+ Row row = sheet.createRow((short) 2);\r
+ row.setHeightInPoints(30);\r
+ for (int i = 0; i < 8; i++) {\r
+ //column width is set in units of 1/256th of a character width\r
+ sheet.setColumnWidth(i, 256*15);\r
+ }\r
\r
- createCell(wb, row, (short) 0, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_BOTTOM);\r
- createCell(wb, row, (short) 1, XSSFCellStyle.ALIGN_CENTER_SELECTION, XSSFCellStyle.VERTICAL_BOTTOM);\r
- createCell(wb, row, (short) 2, XSSFCellStyle.ALIGN_FILL, XSSFCellStyle.VERTICAL_CENTER);\r
- createCell(wb, row, (short) 3, XSSFCellStyle.ALIGN_GENERAL, XSSFCellStyle.VERTICAL_CENTER);\r
- createCell(wb, row, (short) 4, XSSFCellStyle.ALIGN_JUSTIFY, XSSFCellStyle.VERTICAL_JUSTIFY);\r
- createCell(wb, row, (short) 5, XSSFCellStyle.ALIGN_LEFT, XSSFCellStyle.VERTICAL_TOP);\r
- createCell(wb, row, (short) 6, XSSFCellStyle.ALIGN_RIGHT, XSSFCellStyle.VERTICAL_TOP);\r
+ createCell(wb, row, (short) 0, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_BOTTOM);\r
+ createCell(wb, row, (short) 1, XSSFCellStyle.ALIGN_CENTER_SELECTION, XSSFCellStyle.VERTICAL_BOTTOM);\r
+ createCell(wb, row, (short) 2, XSSFCellStyle.ALIGN_FILL, XSSFCellStyle.VERTICAL_CENTER);\r
+ createCell(wb, row, (short) 3, XSSFCellStyle.ALIGN_GENERAL, XSSFCellStyle.VERTICAL_CENTER);\r
+ createCell(wb, row, (short) 4, XSSFCellStyle.ALIGN_JUSTIFY, XSSFCellStyle.VERTICAL_JUSTIFY);\r
+ createCell(wb, row, (short) 5, XSSFCellStyle.ALIGN_LEFT, XSSFCellStyle.VERTICAL_TOP);\r
+ createCell(wb, row, (short) 6, XSSFCellStyle.ALIGN_RIGHT, XSSFCellStyle.VERTICAL_TOP);\r
\r
- // Write the output to a file\r
- FileOutputStream fileOut = new FileOutputStream("aligning.xlsx");\r
- wb.write(fileOut);\r
- fileOut.close();\r
+ // Write the output to a file\r
+ FileOutputStream fileOut = new FileOutputStream("xssf-align.xlsx");\r
+ wb.write(fileOut);\r
+ fileOut.close();\r
\r
- }\r
+ }\r
\r
- /**\r
- * Creates a cell and aligns it a certain way.\r
- *\r
- * @param wb the workbook\r
- * @param row the row to create the cell in\r
- * @param column the column number to create the cell in\r
- * @param halign the horizontal alignment for the cell.\r
- */\r
- private static void createCell(Workbook wb, Row row, short column, short halign, short valign)\r
- {\r
- Cell cell = row.createCell(column);\r
- cell.setCellValue(new XSSFRichTextString("Align It"));\r
- CellStyle cellStyle = wb.createCellStyle();\r
- cellStyle.setAlignment(halign);\r
- cellStyle.setVerticalAlignment(valign);\r
- cell.setCellStyle(cellStyle);\r
- }\r
+ /**\r
+ * Creates a cell and aligns it a certain way.\r
+ *\r
+ * @param wb the workbook\r
+ * @param row the row to create the cell in\r
+ * @param column the column number to create the cell in\r
+ * @param halign the horizontal alignment for the cell.\r
+ */\r
+ private static void createCell(Workbook wb, Row row, short column, short halign, short valign) {\r
+ Cell cell = row.createCell(column);\r
+ cell.setCellValue(new XSSFRichTextString("Align It"));\r
+ CellStyle cellStyle = wb.createCellStyle();\r
+ cellStyle.setAlignment(halign);\r
+ cellStyle.setVerticalAlignment(valign);\r
+ cell.setCellStyle(cellStyle);\r
+ }\r
\r
}\r
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel.examples;\r
+\r
+import org.apache.poi.xssf.usermodel.*;\r
+import org.apache.poi.ss.util.CellRangeAddress;\r
+import org.apache.poi.ss.usermodel.*;\r
+\r
+import java.io.FileOutputStream;\r
+import java.util.Calendar;\r
+import java.util.Map;\r
+import java.util.HashMap;\r
+\r
+/**\r
+ * A monthly calendar created using Apache POI. Each month is on a separate sheet.\r
+ * <pre>\r
+ * Usage:\r
+ * CalendarDemo <year>\r
+ * </pre>\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class CalendarDemo {\r
+\r
+ private static final String[] days = {\r
+ "Sunday", "Monday", "Tuesday",\r
+ "Wednesday", "Thursday", "Friday", "Saturday"};\r
+\r
+ private static final String[] months = {\r
+ "January", "February", "March","April", "May", "June","July", "August",\r
+ "September","October", "November", "December"};\r
+\r
+ public static void main(String[] args) throws Exception {\r
+\r
+ Calendar calendar = Calendar.getInstance();\r
+ if(args.length > 0) calendar.set(Calendar.YEAR, Integer.parseInt(args[0]));\r
+\r
+ int year = calendar.get(Calendar.YEAR);\r
+\r
+ XSSFWorkbook wb = new XSSFWorkbook();\r
+ Map<String, XSSFCellStyle> styles = createStyles(wb);\r
+\r
+ for (int month = 0; month < 12; month++) {\r
+ calendar.set(Calendar.MONTH, month);\r
+ calendar.set(Calendar.DAY_OF_MONTH, 1);\r
+ //create a sheet for each month\r
+ XSSFSheet sheet = wb.createSheet(months[month]);\r
+\r
+ //turn off gridlines\r
+ sheet.setDisplayGridlines(false);\r
+ sheet.setPrintGridlines(false);\r
+ XSSFPrintSetup printSetup = sheet.getPrintSetup();\r
+ printSetup.setOrientation(PrintOrientation.LANDSCAPE);\r
+ sheet.setFitToPage(true);\r
+ sheet.setHorizontallyCenter(true);\r
+\r
+ //the header row: centered text in 48pt font\r
+ XSSFRow headerRow = sheet.createRow(0);\r
+ headerRow.setHeightInPoints(80);\r
+ XSSFCell titleCell = headerRow.createCell(0);\r
+ titleCell.setCellValue(months[month] + " " + year);\r
+ titleCell.setCellStyle(styles.get("title"));\r
+ sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));\r
+\r
+ //header with month titles\r
+ XSSFRow monthRow = sheet.createRow(1);\r
+ for (int i = 0; i < days.length; i++) {\r
+ //for compatibility with HSSF we have to set column width in units of 1/256th of a character width\r
+ sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide\r
+ sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide\r
+ sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1));\r
+ XSSFCell monthCell = monthRow.createCell(i*2);\r
+ monthCell.setCellValue(days[i]);\r
+ monthCell.setCellStyle(styles.get("month"));\r
+ }\r
+\r
+ int cnt = 1, day=1;\r
+ int rownum = 2;\r
+ for (int j = 0; j < 6; j++) {\r
+ XSSFRow row = sheet.createRow(rownum++);\r
+ row.setHeightInPoints(100);\r
+ for (int i = 0; i < days.length; i++) {\r
+ XSSFCell dayCell_1 = row.createCell(i*2);\r
+ XSSFCell dayCell_2 = row.createCell(i*2 + 1);\r
+\r
+ int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);\r
+ if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {\r
+ dayCell_1.setCellValue(day);\r
+ calendar.set(Calendar.DAY_OF_MONTH, ++day);\r
+\r
+ if(i == 0 || i == days.length-1) {\r
+ dayCell_1.setCellStyle(styles.get("weekend_left"));\r
+ dayCell_2.setCellStyle(styles.get("weekend_right"));\r
+ } else {\r
+ dayCell_1.setCellStyle(styles.get("workday_left"));\r
+ dayCell_2.setCellStyle(styles.get("workday_right"));\r
+ }\r
+ } else {\r
+ dayCell_1.setCellStyle(styles.get("grey_left"));\r
+ dayCell_2.setCellStyle(styles.get("grey_right"));\r
+ }\r
+ cnt++;\r
+ }\r
+ if(calendar.get(Calendar.MONTH) > month) break;\r
+ }\r
+ }\r
+\r
+ // Write the output to a file\r
+ FileOutputStream out = new FileOutputStream("calendar-"+year+".xlsx");\r
+ wb.write(out);\r
+ out.close();\r
+ }\r
+\r
+ /**\r
+ * cell styles used for formatting calendar sheets\r
+ */\r
+ public static Map<String, XSSFCellStyle> createStyles(XSSFWorkbook wb){\r
+ Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();\r
+\r
+ XSSFCellStyle style;\r
+ XSSFFont titleFont = wb.createFont();\r
+ titleFont.setFontHeightInPoints((short)48);\r
+ titleFont.setColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.CENTER);\r
+ style.setFont(titleFont);\r
+ styles.put("title", style);\r
+\r
+ XSSFFont monthFont = wb.createFont();\r
+ monthFont.setFontHeightInPoints((short)12);\r
+ monthFont.setColor(new XSSFColor(new java.awt.Color(255, 255, 255)));\r
+ monthFont.setBold(true);\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.CENTER);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setFont(monthFont);\r
+ styles.put("month", style);\r
+\r
+ XSSFFont dayFont = wb.createFont();\r
+ dayFont.setFontHeightInPoints((short)14);\r
+ dayFont.setBold(true);\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.LEFT);\r
+ style.setVerticalAlignment(VerticalAlignment.TOP);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setBorderLeft(BorderStyle.THIN);\r
+ style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setBorderBottom(BorderStyle.THIN);\r
+ style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setFont(dayFont);\r
+ styles.put("weekend_left", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.TOP);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setBorderRight(BorderStyle.THIN);\r
+ style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setBorderBottom(BorderStyle.THIN);\r
+ style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ styles.put("weekend_right", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.LEFT);\r
+ style.setVerticalAlignment(VerticalAlignment.TOP);\r
+ style.setBorderLeft(BorderStyle.THIN);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setBorderBottom(BorderStyle.THIN);\r
+ style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setFont(dayFont);\r
+ styles.put("workday_left", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.TOP);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setBorderRight(BorderStyle.THIN);\r
+ style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setBorderBottom(BorderStyle.THIN);\r
+ style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ styles.put("workday_right", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setBorderLeft(BorderStyle.THIN);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setBorderBottom(BorderStyle.THIN);\r
+ style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ styles.put("grey_left", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setBorderRight(BorderStyle.THIN);\r
+ style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ style.setBorderBottom(BorderStyle.THIN);\r
+ style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89)));\r
+ styles.put("grey_right", style);\r
+\r
+ return styles;\r
+ }\r
+}\r
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.xssf.usermodel.examples;
-
-import java.io.FileOutputStream;
-
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellStyle;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-
-/**
- * How to use newlines in cells
- */
-public class CellNewlines {
-
- public static void main(String[]args) throws Exception {
- Workbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet();
-
- Row row = sheet.createRow(2);
- Cell cell = row.createCell(2);
- cell.setCellValue("Use \n with word wrap on to create a new line");
-
- //to enable newlines you need set a cell styles with wrap=true
- CellStyle cs = wb.createCellStyle();
- cs.setWrapText(true);
- cell.setCellStyle(cs);
-
- //increase row height to accomodate two lines of text
- row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
-
- //adjust column width to fit the content
- sheet.autoSizeColumn((short)2);
-
- FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
- wb.write(fileOut);
- fileOut.close();
- }
-
-}
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
- *
+ * Illustrates how to create cell and set values of different types.
*/
public class CreateCell {
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.xssf.usermodel.examples;
-
-import java.io.FileOutputStream;
-
-import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
-import org.apache.poi.hssf.usermodel.HSSFPatriarch;
-import org.apache.poi.ss.usermodel.*;
-import org.apache.poi.xssf.usermodel.*;
-
-public class CreateNewSpreadsheet {
- public static void main(String[] args) throws Exception {
- XSSFWorkbook wb = new XSSFWorkbook();
- CreationHelper createHelper = wb.getCreationHelper();
-
- XSSFSheet s1 = wb.createSheet("Sheet One");
- XSSFSheet s2 = wb.createSheet("Sheet Two");
-
- // Create a few cells
- s1.createRow(0);
- s1.createRow(1);
- s1.createRow(2);
- s1.createRow(3);
- s2.createRow(2);
-
- s1.getRow(0).createCell(0).setCellValue(1.2);
- s1.getRow(0).createCell(1).setCellValue(createHelper.createRichTextString("Sheet 1 text"));
- s1.getRow(1).createCell(0).setCellValue(4.22);
- s1.getRow(2).createCell(0).setCellValue(5.44);
- s1.getRow(3).createCell(0).setCellFormula("SUM(A1:A3)");
-
- s2.getRow(2).createCell(1).setCellValue(createHelper.createRichTextString("Sheet 2"));
-
- s1.groupRow(0, 3);
-
- s1.getRow(1).setHeightInPoints(10.4f);
- //s1.setActiveCell("A2");
- //s2.setSelected(true);
-
- // Save
- FileOutputStream fout = new FileOutputStream("NewFile.xlsx");
- wb.write(fout);
- fout.close();
- System.out.println("Done");
- }
-}
public class FillsAndColors {
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet("new sheet");
-
- // Create a row and put some cells in it. Rows are 0 based.
- Row row = sheet.createRow((short) 1);
-
- // Aqua background
- CellStyle style = wb.createCellStyle();
- style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
- style.setFillPattern(CellStyle.BIG_SPOTS);
- Cell cell = row.createCell((short) 1);
- cell.setCellValue(new XSSFRichTextString("X"));
- cell.setCellStyle(style);
-
- // Orange "foreground", foreground being the fill foreground not the font color.
- style = wb.createCellStyle();
- style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
- style.setFillPattern(CellStyle.SOLID_FOREGROUND);
- cell = row.createCell((short) 2);
- cell.setCellValue(new XSSFRichTextString("X"));
- cell.setCellStyle(style);
-
- // Write the output to a file
- FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
- wb.write(fileOut);
- fileOut.close();
+ Sheet sheet = wb.createSheet("new sheet");
+
+ // Create a row and put some cells in it. Rows are 0 based.
+ Row row = sheet.createRow((short) 1);
+
+ // Aqua background
+ CellStyle style = wb.createCellStyle();
+ style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
+ style.setFillPattern(CellStyle.BIG_SPOTS);
+ Cell cell = row.createCell((short) 1);
+ cell.setCellValue(new XSSFRichTextString("X"));
+ cell.setCellStyle(style);
+
+ // Orange "foreground", foreground being the fill foreground not the font color.
+ style = wb.createCellStyle();
+ style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
+ style.setFillPattern(CellStyle.SOLID_FOREGROUND);
+ cell = row.createCell((short) 2);
+ cell.setCellValue(new XSSFRichTextString("X"));
+ cell.setCellStyle(style);
+
+ // Write the output to a file
+ FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx");
+ wb.write(fileOut);
+ fileOut.close();
}
}
public class IterateCells {\r
\r
public static void main(String[] args) throws Exception {\r
- Workbook wb = null;\r
+ Workbook wb = new XSSFWorkbook(args[0]);\r
for (int i = 0; i < wb.getNumberOfSheets(); i++) {\r
Sheet sheet = wb.getSheetAt(i);\r
System.out.println(wb.getSheetName(i));\r
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel.examples;\r
+\r
+import org.apache.poi.xssf.usermodel.*;\r
+import org.apache.poi.ss.usermodel.*;\r
+import org.apache.poi.ss.util.CellRangeAddress;\r
+\r
+import java.util.Map;\r
+import java.util.HashMap;\r
+import java.io.FileOutputStream;\r
+\r
+/**\r
+ * Simple Loan Calculator\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class LoanCalculator {\r
+\r
+ public static void main(String[] args) throws Exception {\r
+ XSSFWorkbook wb = new XSSFWorkbook();\r
+ Map<String, XSSFCellStyle> styles = createStyles(wb);\r
+ XSSFSheet sheet = wb.createSheet("Loan Calculator");\r
+ sheet.setPrintGridlines(false);\r
+ sheet.setDisplayGridlines(false);\r
+\r
+ XSSFPrintSetup printSetup = sheet.getPrintSetup();\r
+ printSetup.setOrientation(PrintOrientation.LANDSCAPE);\r
+ sheet.setFitToPage(true);\r
+ sheet.setHorizontallyCenter(true);\r
+\r
+ sheet.setColumnWidth(0, 3*256);\r
+ sheet.setColumnWidth(1, 3*256);\r
+ sheet.setColumnWidth(2, 11*256);\r
+ sheet.setColumnWidth(3, 14*256);\r
+ sheet.setColumnWidth(4, 14*256);\r
+ sheet.setColumnWidth(5, 14*256);\r
+ sheet.setColumnWidth(6, 14*256);\r
+\r
+ createNames(wb);\r
+\r
+ XSSFRow titleRow = sheet.createRow(0);\r
+ titleRow.setHeightInPoints(35);\r
+ for (int i = 1; i <= 7; i++) {\r
+ titleRow.createCell(i).setCellStyle(styles.get("title"));\r
+ }\r
+ XSSFCell titleCell = titleRow.getCell(2);\r
+ titleCell.setCellValue("Simple Loan Calculator");\r
+ sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1"));\r
+\r
+ XSSFRow row = sheet.createRow(2);\r
+ XSSFCell cell = row.createCell(4);\r
+ cell.setCellValue("Enter values");\r
+ cell.setCellStyle(styles.get("item_right"));\r
+\r
+ row = sheet.createRow(3);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Loan amount");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellStyle(styles.get("input_$"));\r
+\r
+ row = sheet.createRow(4);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Annual interest rate");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellStyle(styles.get("input_%"));\r
+\r
+ row = sheet.createRow(5);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Loan period in years");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellStyle(styles.get("input_i"));\r
+\r
+ row = sheet.createRow(6);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Start date of loan");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellStyle(styles.get("input_d"));\r
+\r
+ row = sheet.createRow(8);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Monthly payment");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")");\r
+ cell.setCellStyle(styles.get("formula_$"));\r
+\r
+ row = sheet.createRow(9);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Number of payments");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")");\r
+ cell.setCellStyle(styles.get("formula_i"));\r
+\r
+ row = sheet.createRow(10);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Total interest");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")");\r
+ cell.setCellStyle(styles.get("formula_$"));\r
+\r
+ row = sheet.createRow(11);\r
+ cell = row.createCell(2);\r
+ cell.setCellValue("Total cost of loan");\r
+ cell.setCellStyle(styles.get("item_left"));\r
+ cell = row.createCell(4);\r
+ cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")");\r
+ cell.setCellStyle(styles.get("formula_$"));\r
+\r
+ sheet.setActiveCell("E4");\r
+\r
+ // Write the output to a file\r
+ FileOutputStream out = new FileOutputStream("loan-calculator.xlsx");\r
+ wb.write(out);\r
+ out.close();\r
+ }\r
+\r
+ /**\r
+ * cell styles used for formatting calendar sheets\r
+ */\r
+ public static Map<String, XSSFCellStyle> createStyles(XSSFWorkbook wb){\r
+ Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();\r
+\r
+ XSSFCellStyle style;\r
+ XSSFFont titleFont = wb.createFont();\r
+ titleFont.setFontHeightInPoints((short)14);\r
+ titleFont.setFontName("Trebuchet MS");\r
+ style = wb.createCellStyle();\r
+ style.setFont(titleFont);\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ styles.put("title", style);\r
+\r
+ XSSFFont itemFont = wb.createFont();\r
+ itemFont.setFontHeightInPoints((short)9);\r
+ itemFont.setFontName("Trebuchet MS");\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.LEFT);\r
+ style.setFont(itemFont);\r
+ styles.put("item_left", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.RIGHT);\r
+ style.setFont(itemFont);\r
+ styles.put("item_right", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.RIGHT);\r
+ style.setFont(itemFont);\r
+ style.setBorderRight(BorderStyle.DOTTED);\r
+ style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderLeft(BorderStyle.DOTTED);\r
+ style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderTop(BorderStyle.DOTTED);\r
+ style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setDataFormat(wb.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)"));\r
+ styles.put("input_$", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.RIGHT);\r
+ style.setFont(itemFont);\r
+ style.setBorderRight(BorderStyle.DOTTED);\r
+ style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderLeft(BorderStyle.DOTTED);\r
+ style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderTop(BorderStyle.DOTTED);\r
+ style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setDataFormat(wb.createDataFormat().getFormat("0.000%"));\r
+ styles.put("input_%", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.RIGHT);\r
+ style.setFont(itemFont);\r
+ style.setBorderRight(BorderStyle.DOTTED);\r
+ style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderLeft(BorderStyle.DOTTED);\r
+ style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderTop(BorderStyle.DOTTED);\r
+ style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setDataFormat(wb.createDataFormat().getFormat("0"));\r
+ styles.put("input_i", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setFont(itemFont);\r
+ style.setDataFormat(wb.createDataFormat().getFormat("m/d/yy"));\r
+ styles.put("input_d", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.RIGHT);\r
+ style.setFont(itemFont);\r
+ style.setBorderRight(BorderStyle.DOTTED);\r
+ style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderLeft(BorderStyle.DOTTED);\r
+ style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderTop(BorderStyle.DOTTED);\r
+ style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setDataFormat(wb.createDataFormat().getFormat("$##,##0.00"));\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ styles.put("formula_$", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.RIGHT);\r
+ style.setFont(itemFont);\r
+ style.setBorderRight(BorderStyle.DOTTED);\r
+ style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderLeft(BorderStyle.DOTTED);\r
+ style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setBorderTop(BorderStyle.DOTTED);\r
+ style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setDataFormat(wb.createDataFormat().getFormat("0"));\r
+ style.setBorderBottom(BorderStyle.DOTTED);\r
+ style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ styles.put("formula_i", style);\r
+\r
+ return styles;\r
+ }\r
+\r
+ //define named ranges for the inputs and formulas\r
+ public static void createNames(XSSFWorkbook wb){\r
+ XSSFName name;\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Header_Row");\r
+ name.setReference("ROW('Loan Calculator'!#REF!)");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Interest_Rate");\r
+ name.setReference("'Loan Calculator'!$E$5");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Loan_Amount");\r
+ name.setReference("'Loan Calculator'!$E$4");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Loan_Not_Paid");\r
+ name.setReference("F(Payment_Number<=Number_of_Payments,1,0)");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Loan_Start");\r
+ name.setReference("'Loan Calculator'!$E$7");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Loan_Years");\r
+ name.setReference("'Loan Calculator'!$E$6");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Monthly_Payment");\r
+ name.setReference("-PMT(Interest_Rate/12,Number_of_Payments,Loan_Amount)");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Number_of_Payments");\r
+ name.setReference("'Loan Calculator'!$E$10");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Payment_Number");\r
+ name.setReference("ROW()-Header_Row");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Principal");\r
+ name.setReference("-PPMT(Interest_Rate/12,Payment_Number,Number_of_Payments,Loan_Amount)");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Total_Cost");\r
+ name.setReference("'Loan Calculator'!$E$12");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Total_Interest");\r
+ name.setReference("'Loan Calculator'!$E$11");\r
+\r
+ name = wb.createName();\r
+ name.setNameName("Values_Entered");\r
+ name.setReference("IF(Loan_Amount*Interest_Rate*Loan_Years*Loan_Start>0,1,0)");\r
+\r
+\r
+ }\r
+}\r
import java.io.FileOutputStream;\r
\r
/**\r
- * Merging cells\r
+ * An example of how to merge regions of cells.\r
*/\r
public class MergingCells {\r
public static void main(String[] args) throws Exception {\r
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+==================================================================== */
+package org.apache.poi.xssf.usermodel.examples;
+
+import java.io.FileOutputStream;
+
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+/**
+ * How to use newlines in cells
+ */
+public class NewLinesInCells {
+
+ public static void main(String[]args) throws Exception {
+ Workbook wb = new XSSFWorkbook();
+ Sheet sheet = wb.createSheet();
+
+ Row row = sheet.createRow(2);
+ Cell cell = row.createCell(2);
+ cell.setCellValue("Use \n with word wrap on to create a new line");
+
+ //to enable newlines you need set a cell styles with wrap=true
+ CellStyle cs = wb.createCellStyle();
+ cs.setWrapText(true);
+ cell.setCellStyle(cs);
+
+ //increase row height to accomodate two lines of text
+ row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
+
+ //adjust column width to fit the content
+ sheet.autoSizeColumn((short)2);
+
+ FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
+ wb.write(fileOut);
+ fileOut.close();
+ }
+
+}
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel.examples;\r
+\r
+import org.apache.poi.xssf.usermodel.*;\r
+import org.apache.poi.ss.util.CellRangeAddress;\r
+import org.apache.poi.ss.usermodel.*;\r
+\r
+import java.util.Map;\r
+import java.util.HashMap;\r
+import java.io.FileOutputStream;\r
+\r
+/**\r
+ * A weekly timesheet created using Apache POI.\r
+ *\r
+ * @author Yegor Kozlov\r
+ */\r
+public class TimesheetDemo {\r
+ private static final String[] titles = {\r
+ "Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",\r
+ "Total\nHrs", "Overtime\nHrs", "Regular\nHrs"\r
+ };\r
+\r
+ private static Object[][] sample_data = {\r
+ {"Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0},\r
+ {"Gisella Bronsetti", "GB", 4.0, 3.0, 1.0, 3.5, null, null, 4.0},\r
+ };\r
+\r
+ public static void main(String[] args) throws Exception {\r
+\r
+ XSSFWorkbook wb = new XSSFWorkbook();\r
+ Map<String, XSSFCellStyle> styles = createStyles(wb);\r
+\r
+ XSSFSheet sheet = wb.createSheet("Timesheet");\r
+ XSSFPrintSetup printSetup = sheet.getPrintSetup();\r
+ printSetup.setOrientation(PrintOrientation.LANDSCAPE);\r
+ sheet.setFitToPage(true);\r
+ sheet.setHorizontallyCenter(true);\r
+\r
+ //title row\r
+ XSSFRow titleRow = sheet.createRow(0);\r
+ titleRow.setHeightInPoints(45);\r
+ XSSFCell titleCell = titleRow.createCell(0);\r
+ titleCell.setCellValue("Weekly Timesheet");\r
+ titleCell.setCellStyle(styles.get("title"));\r
+ sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));\r
+\r
+ //header row\r
+ XSSFRow headerRow = sheet.createRow(1);\r
+ headerRow.setHeightInPoints(40);\r
+ XSSFCell headerCell;\r
+ for (int i = 0; i < titles.length; i++) {\r
+ headerCell = headerRow.createCell(i);\r
+ headerCell.setCellValue(titles[i]);\r
+ headerCell.setCellStyle(styles.get("header"));\r
+ }\r
+\r
+ int rownum = 2;\r
+ for (int i = 0; i < 10; i++) {\r
+ XSSFRow row = sheet.createRow(rownum++);\r
+ for (int j = 0; j < titles.length; j++) {\r
+ XSSFCell cell = row.createCell(j);\r
+ if(j == 9){\r
+ //the 10th cell contains sum over week days, e.g. SUM(C3:I3)\r
+ String ref = "C" +rownum+ ":I" + rownum;\r
+ cell.setCellFormula("SUM("+ref+")");\r
+ cell.setCellStyle(styles.get("formula"));\r
+ } else if (j == 11){\r
+ cell.setCellFormula("J" +rownum+ "-K" + rownum);\r
+ cell.setCellStyle(styles.get("formula"));\r
+ } else {\r
+ cell.setCellStyle(styles.get("cell"));\r
+ }\r
+ }\r
+ }\r
+\r
+ //row with totals below\r
+ XSSFRow sumRow = sheet.createRow(rownum++);\r
+ sumRow.setHeightInPoints(35);\r
+ XSSFCell cell;\r
+ cell = sumRow.createCell(0);\r
+ cell.setCellStyle(styles.get("formula"));\r
+ cell = sumRow.createCell(1);\r
+ cell.setCellValue("Total Hrs:");\r
+ cell.setCellStyle(styles.get("formula"));\r
+\r
+ for (int j = 2; j < 12; j++) {\r
+ cell = sumRow.createCell(j);\r
+ String ref = (char)('A' + j) + "3:" + (char)('A' + j) + "12";\r
+ cell.setCellFormula("SUM(" + ref + ")");\r
+ if(j >= 9) cell.setCellStyle(styles.get("formula_2"));\r
+ else cell.setCellStyle(styles.get("formula"));\r
+ }\r
+ rownum++;\r
+ sumRow = sheet.createRow(rownum++);\r
+ sumRow.setHeightInPoints(25);\r
+ cell = sumRow.createCell(0);\r
+ cell.setCellValue("Total Regular Hours");\r
+ cell.setCellStyle(styles.get("formula"));\r
+ cell = sumRow.createCell(1);\r
+ cell.setCellFormula("L13");\r
+ cell.setCellStyle(styles.get("formula_2"));\r
+ sumRow = sheet.createRow(rownum++);\r
+ sumRow.setHeightInPoints(25);\r
+ cell = sumRow.createCell(0);\r
+ cell.setCellValue("Total Overtime Hours");\r
+ cell.setCellStyle(styles.get("formula"));\r
+ cell = sumRow.createCell(1);\r
+ cell.setCellFormula("K13");\r
+ cell.setCellStyle(styles.get("formula_2"));\r
+\r
+ //set sample data\r
+ for (int i = 0; i < sample_data.length; i++) {\r
+ XSSFRow row = sheet.getRow(2 + i);\r
+ for (int j = 0; j < sample_data[i].length; j++) {\r
+ if(sample_data[i][j] == null) continue;\r
+\r
+ if(sample_data[i][j] instanceof String) {\r
+ row.getCell(j).setCellValue((String)sample_data[i][j]);\r
+ } else {\r
+ row.getCell(j).setCellValue((Double)sample_data[i][j]);\r
+ }\r
+ }\r
+ }\r
+\r
+ //finally set column widths\r
+ sheet.setColumnWidth(0, 30*256);\r
+ for (int i = 2; i < 9; i++) {\r
+ sheet.setColumnWidth(i, 6*256);\r
+ }\r
+\r
+ // Write the output to a file\r
+ FileOutputStream out = new FileOutputStream("ooxml-timesheet.xlsx");\r
+ wb.write(out);\r
+ out.close();\r
+ }\r
+\r
+ public static Map<String, XSSFCellStyle> createStyles(XSSFWorkbook wb){\r
+ Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();\r
+ XSSFCellStyle style;\r
+ XSSFFont titleFont = wb.createFont();\r
+ titleFont.setFontHeightInPoints((short)18);\r
+ titleFont.setBold(true);\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.CENTER);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setFont(titleFont);\r
+ styles.put("title", style);\r
+\r
+ XSSFFont monthFont = wb.createFont();\r
+ monthFont.setFontHeightInPoints((short)11);\r
+ monthFont.setColor(new XSSFColor(new java.awt.Color(255, 255, 255)));\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.CENTER);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(102, 102, 102)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setFont(monthFont);\r
+ style.setWrapText(true);\r
+ styles.put("header", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setWrapText(true);\r
+ style.setBorderRight(BorderStyle.THIN);\r
+ style.setRightBorderColor(IndexedColors.BLACK.getIndex());\r
+ style.setBorderLeft(BorderStyle.THIN);\r
+ style.setLeftBorderColor(IndexedColors.BLACK.getIndex());\r
+ style.setBorderTop(BorderStyle.THIN);\r
+ style.setTopBorderColor(IndexedColors.BLACK.getIndex());\r
+ style.setBorderBottom(BorderStyle.THIN);\r
+ style.setBottomBorderColor(IndexedColors.BLACK.getIndex());\r
+ styles.put("cell", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.CENTER);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setDataFormat(wb.createDataFormat().getFormat("0.00"));\r
+ styles.put("formula", style);\r
+\r
+ style = wb.createCellStyle();\r
+ style.setAlignment(HorizontalAlignment.CENTER);\r
+ style.setVerticalAlignment(VerticalAlignment.CENTER);\r
+ style.setFillForegroundColor(new XSSFColor(new java.awt.Color(192, 192, 192)));\r
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);\r
+ style.setDataFormat(wb.createDataFormat().getFormat("0.00"));\r
+ styles.put("formula_2", style);\r
+\r
+ return styles;\r
+ }\r
+}\r
public class WorkingWithBorders {\r
public static void main(String[] args) throws Exception {\r
Workbook wb = new XSSFWorkbook();\r
- Sheet sheet = wb.createSheet("new sheet");\r
+ Sheet sheet = wb.createSheet("borders");\r
\r
// Create a row and put some cells in it. Rows are 0 based.\r
Row row = sheet.createRow((short) 1);\r
cell.setCellStyle(style);\r
\r
// Write the output to a file\r
- FileOutputStream fileOut = new FileOutputStream("workbook_borders.xlsx");\r
+ FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx");\r
wb.write(fileOut);\r
fileOut.close();\r
\r
wb.setPrintArea(0, 1, 2, 0, 3);
- FileOutputStream fileOut = new FileOutputStream("ooxml-printsetup.xlsx");
+ FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx");
wb.write(fileOut);
fileOut.close();
}
import java.io.FileOutputStream;\r
\r
/**\r
- * Demonstrates how to work with rich text\r
+ * Demonstrates how to work with rich text\r
*/\r
public class WorkingWithRichText {\r
\r
- public static void main(String[] args)\r
- throws Exception\r
- {\r
- XSSFWorkbook wb = new XSSFWorkbook();\r
+ public static void main(String[] args) throws Exception {\r
+ \r
+ XSSFWorkbook wb = new XSSFWorkbook();\r
\r
- XSSFSheet sheet = wb.createSheet();\r
- XSSFRow row = sheet.createRow((short) 2);\r
+ XSSFSheet sheet = wb.createSheet();\r
+ XSSFRow row = sheet.createRow((short) 2);\r
\r
- XSSFCell cell = row.createCell(1);\r
- XSSFRichTextString rt = new XSSFRichTextString("The quick");\r
+ XSSFCell cell = row.createCell(1);\r
+ XSSFRichTextString rt = new XSSFRichTextString("The quick");\r
\r
- XSSFFont font1 = wb.createFont();\r
- font1.setBold(true);\r
- rt.append(" brown fox", font1);\r
+ XSSFFont font1 = wb.createFont();\r
+ font1.setBold(true);\r
+ rt.append(" brown fox", font1);\r
\r
- XSSFFont font2 = wb.createFont();\r
- font2.setItalic(true);\r
- font2.setColor(IndexedColors.RED.getIndex());\r
- rt.applyFont((short)0);\r
- cell.setCellValue(rt);\r
+ XSSFFont font2 = wb.createFont();\r
+ font2.setItalic(true);\r
+ font2.setColor(IndexedColors.RED.getIndex());\r
+ rt.applyFont((short) 0);\r
+ cell.setCellValue(rt);\r
\r
- // Write the output to a file\r
- FileOutputStream fileOut = new FileOutputStream("rich_text.xlsx");\r
- wb.write(fileOut);\r
- fileOut.close();\r
+ // Write the output to a file\r
+ FileOutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx");\r
+ wb.write(fileOut);\r
+ fileOut.close();\r
\r
- }\r
+ }\r
\r
- }\r
+}\r
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.ss.usermodel;\r
+\r
+import java.util.regex.Pattern;\r
+import java.util.regex.Matcher;\r
+import java.util.*;\r
+import java.text.*;\r
+\r
+/**\r
+ * DataFormatter contains methods for formatting the value stored in an\r
+ * Cell. This can be useful for reports and GUI presentations when you\r
+ * need to display data exactly as it appears in Excel. Supported formats\r
+ * include currency, SSN, percentages, decimals, dates, phone numbers, zip\r
+ * codes, etc.\r
+ * <p>\r
+ * Internally, formats will be implemented using subclasses of {@link Format}\r
+ * such as {@link DecimalFormat} and {@link SimpleDateFormat}. Therefore the\r
+ * formats used by this class must obey the same pattern rules as these Format\r
+ * subclasses. This means that only legal number pattern characters ("0", "#",\r
+ * ".", "," etc.) may appear in number formats. Other characters can be\r
+ * inserted <em>before</em> or <em> after</em> the number pattern to form a\r
+ * prefix or suffix.\r
+ * </p>\r
+ * <p>\r
+ * For example the Excel pattern <code>"$#,##0.00 "USD"_);($#,##0.00 "USD")"\r
+ * </code> will be correctly formatted as "$1,000.00 USD" or "($1,000.00 USD)".\r
+ * However the pattern <code>"00-00-00"</code> is incorrectly formatted by\r
+ * DecimalFormat as "000000--". For Excel formats that are not compatible with\r
+ * DecimalFormat, you can provide your own custom {@link Format} implementation\r
+ * via <code>DataFormatter.addFormat(String,Format)</code>. The following\r
+ * custom formats are already provided by this class:\r
+ * </p>\r
+ * <pre>\r
+ * <ul><li>SSN "000-00-0000"</li>\r
+ * <li>Phone Number "(###) ###-####"</li>\r
+ * <li>Zip plus 4 "00000-0000"</li>\r
+ * </ul>\r
+ * </pre>\r
+ * <p>\r
+ * If the Excel format pattern cannot be parsed successfully, then a default\r
+ * format will be used. The default number format will mimic the Excel General\r
+ * format: "#" for whole numbers and "#.##########" for decimal numbers. You\r
+ * can override the default format pattern with <code>\r
+ * DataFormatter.setDefaultNumberFormat(Format)</code>. <b>Note:</b> the\r
+ * default format will only be used when a Format cannot be created from the\r
+ * cell's data format string.\r
+ *\r
+ * @author James May (james dot may at fmr dot com)\r
+ *\r
+ */\r
+public class DataFormatter {\r
+\r
+ /** Pattern to find a number format: "0" or "#" */\r
+ private static final Pattern numPattern = Pattern.compile("[0#]+");\r
+\r
+ /** Pattern to find days of week as text "ddd...." */\r
+ private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE);\r
+\r
+ /** Pattern to find "AM/PM" marker */\r
+ private static final Pattern amPmPattern = Pattern.compile("((A|P)[M/P]*)", Pattern.CASE_INSENSITIVE);\r
+\r
+ /** A regex to find patterns like [$$-1009] and [$?-452]. */\r
+ private static final Pattern specialPatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+\\])");\r
+\r
+ /** <em>General</em> format for whole numbers. */\r
+ private static final Format generalWholeNumFormat = new DecimalFormat("#");\r
+\r
+ /** <em>General</em> format for decimal numbers. */\r
+ private static final Format generalDecimalNumFormat = new DecimalFormat("#.##########");\r
+\r
+ /** A default format to use when a number pattern cannot be parsed. */\r
+ private Format defaultNumFormat;\r
+\r
+ /**\r
+ * A map to cache formats.\r
+ * Map<String,Format> formats\r
+ */\r
+ private final Map formats;\r
+\r
+ /**\r
+ * Constructor\r
+ */\r
+ public DataFormatter() {\r
+ formats = new HashMap();\r
+\r
+ // init built-in formats\r
+\r
+ Format zipFormat = ZipPlusFourFormat.instance;\r
+ addFormat("00000\\-0000", zipFormat);\r
+ addFormat("00000-0000", zipFormat);\r
+\r
+ Format phoneFormat = PhoneFormat.instance;\r
+ // allow for format string variations\r
+ addFormat("[<=9999999]###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);\r
+ addFormat("[<=9999999]###-####;(###) ###-####", phoneFormat);\r
+ addFormat("###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);\r
+ addFormat("###-####;(###) ###-####", phoneFormat);\r
+\r
+ Format ssnFormat = SSNFormat.instance;\r
+ addFormat("000\\-00\\-0000", ssnFormat);\r
+ addFormat("000-00-0000", ssnFormat);\r
+ }\r
+\r
+ /**\r
+ * Return a Format for the given cell if one exists, otherwise try to\r
+ * create one. This method will return <code>null</code> if the any of the\r
+ * following is true:\r
+ * <ul>\r
+ * <li>the cell's style is null</li>\r
+ * <li>the style's data format string is null or empty</li>\r
+ * <li>the format string cannot be recognized as either a number or date</li>\r
+ * </ul>\r
+ *\r
+ * @param cell The cell to retrieve a Format for\r
+ * @return A Format for the format String\r
+ */\r
+ private Format getFormat(Cell cell) {\r
+ if ( cell.getCellStyle() == null) {\r
+ return null;\r
+ }\r
+\r
+ int formatIndex = cell.getCellStyle().getDataFormat();\r
+ String formatStr = cell.getCellStyle().getDataFormatString();\r
+ if(formatStr == null || formatStr.trim().length() == 0) {\r
+ return null;\r
+ }\r
+ return getFormat(cell.getNumericCellValue(), formatIndex, formatStr);\r
+ }\r
+\r
+ private Format getFormat(double cellValue, int formatIndex, String formatStr) {\r
+ Format format = (Format)formats.get(formatStr);\r
+ if (format != null) {\r
+ return format;\r
+ }\r
+ if (formatStr.equals("General")) {\r
+ if (DataFormatter.isWholeNumber(cellValue)) {\r
+ return generalWholeNumFormat;\r
+ }\r
+ return generalDecimalNumFormat;\r
+ }\r
+ format = createFormat(cellValue, formatIndex, formatStr);\r
+ formats.put(formatStr, format);\r
+ return format;\r
+ }\r
+\r
+ /**\r
+ * Create and return a Format based on the format string from a cell's\r
+ * style. If the pattern cannot be parsed, return a default pattern.\r
+ *\r
+ * @param cell The Excel cell\r
+ * @return A Format representing the excel format. May return null.\r
+ */\r
+ public Format createFormat(Cell cell) {\r
+\r
+ int formatIndex = cell.getCellStyle().getDataFormat();\r
+ String formatStr = cell.getCellStyle().getDataFormatString();\r
+ return createFormat(cell.getNumericCellValue(), formatIndex, formatStr);\r
+ }\r
+\r
+ private Format createFormat(double cellValue, int formatIndex, String sFormat) {\r
+ // remove color formatting if present\r
+ String formatStr = sFormat.replaceAll("\\[[a-zA-Z]*\\]", "");\r
+\r
+ // try to extract special characters like currency\r
+ Matcher m = specialPatternGroup.matcher(formatStr);\r
+ while(m.find()) {\r
+ String match = m.group();\r
+ String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-'));\r
+ if (symbol.indexOf('$') > -1) {\r
+ StringBuffer sb = new StringBuffer();\r
+ sb.append(symbol.substring(0, symbol.indexOf('$')));\r
+ sb.append('\\');\r
+ sb.append(symbol.substring(symbol.indexOf('$'), symbol.length()));\r
+ symbol = sb.toString();\r
+ }\r
+ formatStr = m.replaceAll(symbol);\r
+ m = specialPatternGroup.matcher(formatStr);\r
+ }\r
+\r
+ if(formatStr == null || formatStr.trim().length() == 0) {\r
+ return getDefaultFormat(cellValue);\r
+ }\r
+\r
+\r
+ if(DateUtil.isADateFormat(formatIndex,formatStr) &&\r
+ DateUtil.isValidExcelDate(cellValue)) {\r
+ return createDateFormat(formatStr, cellValue);\r
+ }\r
+ if (numPattern.matcher(formatStr).find()) {\r
+ return createNumberFormat(formatStr, cellValue);\r
+ }\r
+ // TODO - when does this occur?\r
+ return null;\r
+ }\r
+\r
+ private Format createDateFormat(String pFormatStr, double cellValue) {\r
+ String formatStr = pFormatStr;\r
+ formatStr = formatStr.replaceAll("\\\\-","-");\r
+ formatStr = formatStr.replaceAll("\\\\,",",");\r
+ formatStr = formatStr.replaceAll("\\\\ "," ");\r
+ formatStr = formatStr.replaceAll(";@", "");\r
+ boolean hasAmPm = false;\r
+ Matcher amPmMatcher = amPmPattern.matcher(formatStr);\r
+ while (amPmMatcher.find()) {\r
+ formatStr = amPmMatcher.replaceAll("@");\r
+ hasAmPm = true;\r
+ amPmMatcher = amPmPattern.matcher(formatStr);\r
+ }\r
+ formatStr = formatStr.replaceAll("@", "a");\r
+\r
+\r
+ Matcher dateMatcher = daysAsText.matcher(formatStr);\r
+ if (dateMatcher.find()) {\r
+ String match = dateMatcher.group(0);\r
+ formatStr = dateMatcher.replaceAll(match.toUpperCase().replaceAll("D", "E"));\r
+ }\r
+\r
+ // Convert excel date format to SimpleDateFormat.\r
+ // Excel uses lower case 'm' for both minutes and months.\r
+ // From Excel help:\r
+ /*\r
+ The "m" or "mm" code must appear immediately after the "h" or"hh"\r
+ code or immediately before the "ss" code; otherwise, Microsoft\r
+ Excel displays the month instead of minutes."\r
+ */\r
+\r
+ StringBuffer sb = new StringBuffer();\r
+ char[] chars = formatStr.toCharArray();\r
+ boolean mIsMonth = true;\r
+ List ms = new ArrayList();\r
+ for(int j=0; j<chars.length; j++) {\r
+ char c = chars[j];\r
+ if (c == 'h' || c == 'H') {\r
+ mIsMonth = false;\r
+ if (hasAmPm) {\r
+ sb.append('h');\r
+ } else {\r
+ sb.append('H');\r
+ }\r
+ }\r
+ else if (c == 'm') {\r
+ if(mIsMonth) {\r
+ sb.append('M');\r
+ ms.add(\r
+ new Integer(sb.length() -1)\r
+ );\r
+ } else {\r
+ sb.append('m');\r
+ }\r
+ }\r
+ else if (c == 's' || c == 'S') {\r
+ sb.append('s');\r
+ // if 'M' precedes 's' it should be minutes ('m')\r
+ for (int i = 0; i < ms.size(); i++) {\r
+ int index = ((Integer)ms.get(i)).intValue();\r
+ if (sb.charAt(index) == 'M') {\r
+ sb.replace(index, index+1, "m");\r
+ }\r
+ }\r
+ mIsMonth = true;\r
+ ms.clear();\r
+ }\r
+ else if (Character.isLetter(c)) {\r
+ mIsMonth = true;\r
+ ms.clear();\r
+ if (c == 'y' || c == 'Y') {\r
+ sb.append('y');\r
+ }\r
+ else if (c == 'd' || c == 'D') {\r
+ sb.append('d');\r
+ }\r
+ else {\r
+ sb.append(c);\r
+ }\r
+ }\r
+ else {\r
+ sb.append(c);\r
+ }\r
+ }\r
+ formatStr = sb.toString();\r
+\r
+ try {\r
+ return new SimpleDateFormat(formatStr);\r
+ } catch(IllegalArgumentException iae) {\r
+\r
+ // the pattern could not be parsed correctly,\r
+ // so fall back to the default number format\r
+ return getDefaultFormat(cellValue);\r
+ }\r
+\r
+ }\r
+\r
+ private Format createNumberFormat(String formatStr, double cellValue) {\r
+ StringBuffer sb = new StringBuffer(formatStr);\r
+ for (int i = 0; i < sb.length(); i++) {\r
+ char c = sb.charAt(i);\r
+ //handle (#,##0_);\r
+ if (c == '(') {\r
+ int idx = sb.indexOf(")", i);\r
+ if (idx > -1 && sb.charAt(idx -1) == '_') {\r
+ sb.deleteCharAt(idx);\r
+ sb.deleteCharAt(idx - 1);\r
+ sb.deleteCharAt(i);\r
+ i--;\r
+ }\r
+ } else if (c == ')' && i > 0 && sb.charAt(i - 1) == '_') {\r
+ sb.deleteCharAt(i);\r
+ sb.deleteCharAt(i - 1);\r
+ i--;\r
+ // remove quotes and back slashes\r
+ } else if (c == '\\' || c == '"') {\r
+ sb.deleteCharAt(i);\r
+ i--;\r
+\r
+ // for scientific/engineering notation\r
+ } else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') {\r
+ sb.deleteCharAt(i);\r
+ i--;\r
+ }\r
+ }\r
+\r
+ try {\r
+ return new DecimalFormat(sb.toString());\r
+ } catch(IllegalArgumentException iae) {\r
+\r
+ // the pattern could not be parsed correctly,\r
+ // so fall back to the default number format\r
+ return getDefaultFormat(cellValue);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Return true if the double value represents a whole number\r
+ * @param d the double value to check\r
+ * @return <code>true</code> if d is a whole number\r
+ */\r
+ private static boolean isWholeNumber(double d) {\r
+ return d == Math.floor(d);\r
+ }\r
+\r
+ /**\r
+ * Returns a default format for a cell.\r
+ * @param cell The cell\r
+ * @return a default format\r
+ */\r
+ public Format getDefaultFormat(Cell cell) {\r
+ return getDefaultFormat(cell.getNumericCellValue());\r
+ }\r
+ private Format getDefaultFormat(double cellValue) {\r
+ // for numeric cells try user supplied default\r
+ if (defaultNumFormat != null) {\r
+ return defaultNumFormat;\r
+\r
+ // otherwise use general format\r
+ }\r
+ if (isWholeNumber(cellValue)){\r
+ return generalWholeNumFormat;\r
+ }\r
+ return generalDecimalNumFormat;\r
+ }\r
+\r
+ /**\r
+ * Returns the formatted value of an Excel date as a <tt>String</tt> based\r
+ * on the cell's <code>DataFormat</code>. i.e. "Thursday, January 02, 2003"\r
+ * , "01/02/2003" , "02-Jan" , etc.\r
+ *\r
+ * @param cell The cell\r
+ * @return a formatted date string\r
+ */\r
+ private String getFormattedDateString(Cell cell) {\r
+ Format dateFormat = getFormat(cell);\r
+ Date d = cell.getDateCellValue();\r
+ if (dateFormat != null) {\r
+ return dateFormat.format(d);\r
+ }\r
+ return d.toString();\r
+ }\r
+\r
+ /**\r
+ * Returns the formatted value of an Excel number as a <tt>String</tt>\r
+ * based on the cell's <code>DataFormat</code>. Supported formats include\r
+ * currency, percents, decimals, phone number, SSN, etc.:\r
+ * "61.54%", "$100.00", "(800) 555-1234".\r
+ *\r
+ * @param cell The cell\r
+ * @return a formatted number string\r
+ */\r
+ private String getFormattedNumberString(Cell cell) {\r
+\r
+ Format numberFormat = getFormat(cell);\r
+ double d = cell.getNumericCellValue();\r
+ if (numberFormat == null) {\r
+ return String.valueOf(d);\r
+ }\r
+ return numberFormat.format(new Double(d));\r
+ }\r
+\r
+ /**\r
+ * Formats the given raw cell value, based on the supplied\r
+ * format index and string, according to excel style rules.\r
+ * @see #formatCellValue(Cell)\r
+ */\r
+ public String formatRawCellContents(double value, int formatIndex, String formatString) {\r
+ // Is it a date?\r
+ if(DateUtil.isADateFormat(formatIndex,formatString) &&\r
+ DateUtil.isValidExcelDate(value)) {\r
+\r
+ Format dateFormat = getFormat(value, formatIndex, formatString);\r
+ Date d = DateUtil.getJavaDate(value);\r
+ if (dateFormat == null) {\r
+ return d.toString();\r
+ }\r
+ return dateFormat.format(d);\r
+ }\r
+ // else Number\r
+ Format numberFormat = getFormat(value, formatIndex, formatString);\r
+ if (numberFormat == null) {\r
+ return String.valueOf(value);\r
+ }\r
+ return numberFormat.format(new Double(value));\r
+ }\r
+\r
+ /**\r
+ * <p>\r
+ * Returns the formatted value of a cell as a <tt>String</tt> regardless\r
+ * of the cell type. If the Excel format pattern cannot be parsed then the\r
+ * cell value will be formatted using a default format.\r
+ * </p>\r
+ * <p>When passed a null or blank cell, this method will return an empty\r
+ * String (""). Formulas in formula type cells will not be evaluated.\r
+ * </p>\r
+ *\r
+ * @param cell The cell\r
+ * @return the formatted cell value as a String\r
+ */\r
+ public String formatCellValue(Cell cell) {\r
+ return formatCellValue(cell, null);\r
+ }\r
+\r
+ /**\r
+ * <p>\r
+ * Returns the formatted value of a cell as a <tt>String</tt> regardless\r
+ * of the cell type. If the Excel format pattern cannot be parsed then the\r
+ * cell value will be formatted using a default format.\r
+ * </p>\r
+ * <p>When passed a null or blank cell, this method will return an empty\r
+ * String (""). Formula cells will be evaluated using the given\r
+ * {@link FormulaEvaluator} if the evaluator is non-null. If the\r
+ * evaluator is null, then the formula String will be returned. The caller\r
+ * is responsible for setting the currentRow on the evaluator\r
+ *</p>\r
+ *\r
+ * @param cell The cell (can be null)\r
+ * @param evaluator The FormulaEvaluator (can be null)\r
+ * @return a string value of the cell\r
+ */\r
+ public String formatCellValue(Cell cell,\r
+ FormulaEvaluator evaluator) throws IllegalArgumentException {\r
+\r
+ if (cell == null) {\r
+ return "";\r
+ }\r
+\r
+ int cellType = cell.getCellType();\r
+ if (evaluator != null && cellType == Cell.CELL_TYPE_FORMULA) {\r
+ try {\r
+ cellType = evaluator.evaluateFormulaCell(cell);\r
+ } catch (RuntimeException e) {\r
+ throw new RuntimeException("Did you forget to set the current" +\r
+ " row on the FormulaEvaluator?", e);\r
+ }\r
+ }\r
+ switch (cellType)\r
+ {\r
+ case Cell.CELL_TYPE_FORMULA :\r
+ // should only occur if evaluator is null\r
+ return cell.getCellFormula();\r
+\r
+ case Cell.CELL_TYPE_NUMERIC :\r
+\r
+ if (DateUtil.isCellDateFormatted(cell)) {\r
+ return getFormattedDateString(cell);\r
+ }\r
+ return getFormattedNumberString(cell);\r
+\r
+ case Cell.CELL_TYPE_STRING :\r
+ return cell.getRichStringCellValue().getString();\r
+\r
+ case Cell.CELL_TYPE_BOOLEAN :\r
+ return String.valueOf(cell.getBooleanCellValue());\r
+ case Cell.CELL_TYPE_BLANK :\r
+ return "";\r
+ }\r
+ throw new RuntimeException("Unexpected celltype (" + cellType + ")");\r
+ }\r
+\r
+\r
+ /**\r
+ * <p>\r
+ * Sets a default number format to be used when the Excel format cannot be\r
+ * parsed successfully. <b>Note:</b> This is a fall back for when an error\r
+ * occurs while parsing an Excel number format pattern. This will not\r
+ * affect cells with the <em>General</em> format.\r
+ * </p>\r
+ * <p>\r
+ * The value that will be passed to the Format's format method (specified\r
+ * by <code>java.text.Format#format</code>) will be a double value from a\r
+ * numeric cell. Therefore the code in the format method should expect a\r
+ * <code>Number</code> value.\r
+ * </p>\r
+ *\r
+ * @param format A Format instance to be used as a default\r
+ * @see java.text.Format#format\r
+ */\r
+ public void setDefaultNumberFormat(Format format) {\r
+ Iterator itr = formats.entrySet().iterator();\r
+ while(itr.hasNext()) {\r
+ Map.Entry entry = (Map.Entry)itr.next();\r
+ if (entry.getValue() == generalDecimalNumFormat\r
+ || entry.getValue() == generalWholeNumFormat) {\r
+ entry.setValue(format);\r
+ }\r
+ }\r
+ defaultNumFormat = format;\r
+ }\r
+\r
+ /**\r
+ * Adds a new format to the available formats.\r
+ * <p>\r
+ * The value that will be passed to the Format's format method (specified\r
+ * by <code>java.text.Format#format</code>) will be a double value from a\r
+ * numeric cell. Therefore the code in the format method should expect a\r
+ * <code>Number</code> value.\r
+ * </p>\r
+ * @param excelFormatStr The data format string\r
+ * @param format A Format instance\r
+ */\r
+ public void addFormat(String excelFormatStr, Format format) {\r
+ formats.put(excelFormatStr, format);\r
+ }\r
+\r
+ // Some custom formats\r
+\r
+ /**\r
+ * @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code>\r
+ */\r
+ /* package */ static DecimalFormat createIntegerOnlyFormat(String fmt) {\r
+ DecimalFormat result = new DecimalFormat(fmt);\r
+ result.setParseIntegerOnly(true);\r
+ return result;\r
+ }\r
+ /**\r
+ * Format class for Excel's SSN format. This class mimics Excel's built-in\r
+ * SSN formatting.\r
+ *\r
+ * @author James May\r
+ */\r
+ private static final class SSNFormat extends Format {\r
+ public static final Format instance = new SSNFormat();\r
+ private static final DecimalFormat df = createIntegerOnlyFormat("000000000");\r
+ private SSNFormat() {\r
+ // enforce singleton\r
+ }\r
+\r
+ /** Format a number as an SSN */\r
+ public static String format(Number num) {\r
+ String result = df.format(num);\r
+ StringBuffer sb = new StringBuffer();\r
+ sb.append(result.substring(0, 3)).append('-');\r
+ sb.append(result.substring(3, 5)).append('-');\r
+ sb.append(result.substring(5, 9));\r
+ return sb.toString();\r
+ }\r
+\r
+ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {\r
+ return toAppendTo.append(format((Number)obj));\r
+ }\r
+\r
+ public Object parseObject(String source, ParsePosition pos) {\r
+ return df.parseObject(source, pos);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Format class for Excel Zip + 4 format. This class mimics Excel's\r
+ * built-in formatting for Zip + 4.\r
+ * @author James May\r
+ */\r
+ private static final class ZipPlusFourFormat extends Format {\r
+ public static final Format instance = new ZipPlusFourFormat();\r
+ private static final DecimalFormat df = createIntegerOnlyFormat("000000000");\r
+ private ZipPlusFourFormat() {\r
+ // enforce singleton\r
+ }\r
+\r
+ /** Format a number as Zip + 4 */\r
+ public static String format(Number num) {\r
+ String result = df.format(num);\r
+ StringBuffer sb = new StringBuffer();\r
+ sb.append(result.substring(0, 5)).append('-');\r
+ sb.append(result.substring(5, 9));\r
+ return sb.toString();\r
+ }\r
+\r
+ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {\r
+ return toAppendTo.append(format((Number)obj));\r
+ }\r
+\r
+ public Object parseObject(String source, ParsePosition pos) {\r
+ return df.parseObject(source, pos);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Format class for Excel phone number format. This class mimics Excel's\r
+ * built-in phone number formatting.\r
+ * @author James May\r
+ */\r
+ private static final class PhoneFormat extends Format {\r
+ public static final Format instance = new PhoneFormat();\r
+ private static final DecimalFormat df = createIntegerOnlyFormat("##########");\r
+ private PhoneFormat() {\r
+ // enforce singleton\r
+ }\r
+\r
+ /** Format a number as a phone number */\r
+ public static String format(Number num) {\r
+ String result = df.format(num);\r
+ StringBuffer sb = new StringBuffer();\r
+ String seg1, seg2, seg3;\r
+ int len = result.length();\r
+ if (len <= 4) {\r
+ return result;\r
+ }\r
+\r
+ seg3 = result.substring(len - 4, len);\r
+ seg2 = result.substring(Math.max(0, len - 7), len - 4);\r
+ seg1 = result.substring(Math.max(0, len - 10), Math.max(0, len - 7));\r
+\r
+ if(seg1 != null && seg1.trim().length() > 0) {\r
+ sb.append('(').append(seg1).append(") ");\r
+ }\r
+ if(seg2 != null && seg2.trim().length() > 0) {\r
+ sb.append(seg2).append('-');\r
+ }\r
+ sb.append(seg3);\r
+ return sb.toString();\r
+ }\r
+\r
+ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {\r
+ return toAppendTo.append(format((Number)obj));\r
+ }\r
+\r
+ public Object parseObject(String source, ParsePosition pos) {\r
+ return df.parseObject(source, pos);\r
+ }\r
+ }\r
+}\r
short getAlignment();
/**
- * set whether the text should be wrapped
+ * Set whether the text should be wrapped.
+ * Setting this flag to <code>true</code> make all content visible
+ * whithin a cell by displaying it on multiple lines
+ *
* @param wrapped wrap text or not
*/
void setDefaultRowHeightInPoints(float height);
- /**
- * get whether gridlines are printed.
- * @return true if printed
- */
-
- boolean isGridsPrinted();
-
- /**
- * set whether gridlines printed.
- * @param value false if not printed.
- */
-
- void setGridsPrinted(boolean value);
-
-
/**
* adds a merged region of cells (hence those cells form one)
* @param region (rowfrom/colfrom-rowto/colto) to merge
*/
Iterator<Row> rowIterator();
- /**
- * whether alternate expression evaluation is on
- * @param b alternative expression evaluation or not
- */
-
- void setAlternativeExpression(boolean b);
-
- /**
- * whether alternative formula entry is on
- * @param b alternative formulas or not
- */
-
- void setAlternativeFormula(boolean b);
-
/**
* show automatic page breaks or not
* @param b whether to show auto page breaks
* classes.
*/
CreationHelper getCreationHelper();
+
+ /**
+ * Check whether a sheet is hidden.
+ * Note that a sheet could instead be
+ * set to be very hidden, which is different
+ * ({@link #isSheetVeryHidden(int)})
+ * @param sheetIx Number
+ * @return True if sheet is hidden
+ */
+ public boolean isSheetHidden(int sheetIx) ;
+
+ /**
+ * Check whether a sheet is very hidden.
+ * This is different from the normal
+ * hidden status
+ * ({@link #isSheetHidden(int)})
+ * @param sheetIx Number
+ * @return True if sheet is very hidden
+ */
+ public boolean isSheetVeryHidden(int sheetIx);
+
+ /**
+ * Hide or unhide a sheet
+ *
+ * @param sheetIx The sheet index
+ * @param hidden True to mark the sheet as hidden, false otherwise
+ */
+ public void setSheetHidden(int sheetIx, boolean hidden);
+
+ /**
+ * Hide or unhide a sheet.
+ * 0 = not hidden
+ * 1 = hidden
+ * 2 = very hidden.
+ *
+ * @param sheetIx The sheet number
+ * @param hidden 0 for not hidden, 1 for hidden, 2 for very hidden
+ */
+ public void setSheetHidden(int sheetIx, int hidden);
+
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.List;
+import java.util.*;
import java.util.Map.Entry;
-import org.apache.poi.ss.usermodel.CellStyle;
-import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.FontFamily;
import org.apache.poi.ss.usermodel.FontScheme;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
* @author ugo
*/
public class StylesTable extends POIXMLDocumentPart {
- private final Hashtable<Integer, String> numberFormats = new Hashtable<Integer,String>();
+ private final Map<Integer, String> numberFormats = new LinkedHashMap<Integer,String>();
private final List<XSSFFont> fonts = new ArrayList<XSSFFont>();
private final List<XSSFCellFill> fills = new ArrayList<XSSFCellFill>();
private final List<XSSFCellBorder> borders = new ArrayList<XSSFCellBorder>();
* @param is The input stream containing the XML document.
* @throws IOException if an error occurs while reading.
*/
- public void readFrom(InputStream is) throws IOException {
+ protected void readFrom(InputStream is) throws IOException {
try {
doc = StyleSheetDocument.Factory.parse(is);
// Grab all the different bits we care about
public String getNumberFormatAt(int idx) {
return numberFormats.get(idx);
}
- public synchronized int putNumberFormat(String fmt) {
+
+ public int putNumberFormat(String fmt) {
if (numberFormats.containsValue(fmt)) {
// Find the key, and return that
- for(Enumeration<Integer> keys = numberFormats.keys(); keys.hasMoreElements();) {
- int key = keys.nextElement();
+ for(Integer key : numberFormats.keySet() ) {
if(numberFormats.get(key).equals(fmt)) {
return key;
}
}
public XSSFFont getFontAt(int idx) {
- return fonts.get((int)idx);
+ return fonts.get(idx);
}
- public int putFont(Font font) {
+ public int putFont(XSSFFont font) {
int idx = fonts.indexOf(font);
if (idx != -1) {
return idx;
}
- fonts.add((XSSFFont)font);
+ fonts.add(font);
return fonts.size() - 1;
}
int styleXfId = 0;
// 0 is the empty default
- if(xfs.get((int) idx).getXfId() > 0) {
- styleXfId = (int) xfs.get((int) idx).getXfId();
+ if(xfs.get(idx).getXfId() > 0) {
+ styleXfId = (int) xfs.get(idx).getXfId();
}
- return new XSSFCellStyle((int) idx, styleXfId, this);
+ return new XSSFCellStyle(idx, styleXfId, this);
}
- public synchronized int putStyle(CellStyle style) {
- XSSFCellStyle xStyle = (XSSFCellStyle)style;
- CTXf mainXF = xStyle.getCoreXf();
+ public int putStyle(XSSFCellStyle style) {
+ CTXf mainXF = style.getCoreXf();
if(! xfs.contains(mainXF)) {
xfs.add(mainXF);
return borders.size() - 1;
}
+ public XSSFCellFill getFillAt(int idx) {
+ return fills.get(idx);
+ }
+
public List<XSSFCellBorder> getBorders(){
return borders;
}
- public XSSFCellFill getFillAt(int idx) {
- return fills.get(idx);
- }
-
public List<XSSFCellFill> getFills(){
return fills;
}
+ public List<XSSFFont> getFonts(){
+ return fonts;
+ }
+
+ public Map<Integer, String> getNumberFormats(){
+ return numberFormats;
+ }
+
public int putFill(XSSFCellFill fill) {
int idx = fills.indexOf(fill);
if (idx != -1) {
}
public CTXf getCellXfAt(int idx) {
- return xfs.get((int) idx);
+ return xfs.get(idx);
}
public int putCellXf(CTXf cellXf) {
xfs.add(cellXf);
}
public CTXf getCellStyleXfAt(int idx) {
- return styleXfs.get((int) idx);
+ return styleXfs.get(idx);
}
public int putCellStyleXf(CTXf cellStyleXf) {
styleXfs.add(cellStyleXf);
public int getNumCellStyles(){
return styleXfs.size();
}
- /**
- * get the size of fonts
- */
- public int getNumberOfFonts(){
- return this.fonts.size();
- }
+
/**
* For unit testing only
*/
public int _getNumberFormatSize() {
return numberFormats.size();
}
- /**
- * For unit testing only
- */
- public int _getFontsSize() {
- return fonts.size();
- }
- /**
- * For unit testing only
- */
- public int _getFillsSize() {
- return fills.size();
- }
- /**
- * For unit testing only
- */
- public int _getBordersSize() {
- return borders.size();
- }
+
/**
* For unit testing only
*/
/**
* For unit testing only!
*/
- public CTStylesheet _getRawStylesheet() {
+ public CTStylesheet getCTStylesheet() {
return doc.getStyleSheet();
}
}
doc.getStyleSheet().setNumFmts(formats);
- int idx = 0;
+ int idx;
// Fonts
CTFonts ctFonts = CTFonts.Factory.newInstance();
ctFonts.setCount(fonts.size());
xfs.add(xf);
}
- private CTXf createDefaultXf() {
+ private static CTXf createDefaultXf() {
CTXf ctXf = CTXf.Factory.newInstance();
ctXf.setNumFmtId(0);
ctXf.setFontId(0);
ctXf.setBorderId(0);
return ctXf;
}
- private CTBorder createDefaultBorder() {
+ private static CTBorder createDefaultBorder() {
CTBorder ctBorder = CTBorder.Factory.newInstance();
ctBorder.addNewBottom();
ctBorder.addNewTop();
}
- private CTFill[] createDefaultFills() {
+ private static CTFill[] createDefaultFills() {
CTFill[] ctFill = new CTFill[]{CTFill.Factory.newInstance(),CTFill.Factory.newInstance()};
ctFill[0].addNewPatternFill().setPatternType(STPatternType.NONE);
ctFill[1].addNewPatternFill().setPatternType(STPatternType.DARK_GRAY);
return ctFill;
}
- private XSSFFont createDefaultFont() {
+ private static XSSFFont createDefaultFont() {
CTFont ctFont = CTFont.Factory.newInstance();
XSSFFont xssfFont=new XSSFFont(ctFont, 0);
xssfFont.setFontHeightInPoints(XSSFFont.DEFAULT_FONT_SIZE);
return xssfFont;
}
- public CTDxf getDxf(int idx) {
+ protected CTDxf getDxf(int idx) {
if(dxfs.size()==0)
return CTDxf.Factory.newInstance();
else
- return dxfs.get((int) idx);
+ return dxfs.get(idx);
}
- public int putDxf(CTDxf dxf) {
+ protected int putDxf(CTDxf dxf) {
this.dxfs.add(dxf);
return this.dxfs.size();
}
+
+ public XSSFCellStyle createCellStyle() {
+ CTXf xf = CTXf.Factory.newInstance();
+ xf.setNumFmtId(0);
+ xf.setFontId(0);
+ xf.setFillId(0);
+ xf.setBorderId(0);
+ xf.setXfId(0);
+ int xfSize = styleXfs.size();
+ int indexXf = putCellXf(xf);
+ return new XSSFCellStyle(indexXf - 1, xfSize - 1, this);
+ }
+
+ /**
+ * Finds a font that matches the one with the supplied attributes
+ */
+ public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
+ for (XSSFFont font : fonts) {
+ if ( (font.getBold() == (boldWeight == XSSFFont.BOLDWEIGHT_BOLD))
+ && font.getColor() == color
+ && font.getFontHeightInPoints() == fontHeight
+ && font.getFontName().equals(name)
+ && font.getItalic() == italic
+ && font.getStrikeout() == strikeout
+ && font.getTypeOffset() == typeOffset
+ && font.getUnderline() == underline)
+ {
+ return font;
+ }
+ }
+ return null;
+ }
+
}
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.model.XSSFWritableModel;
+import org.apache.poi.POIXMLException;
import org.openxml4j.opc.PackagePart;
public class XSSFActiveXData implements PictureData, XSSFWritableModel {
try {
return IOUtils.toByteArray(packagePart.getInputStream());
} catch(IOException e) {
- throw new RuntimeException(e);
+ throw new POIXMLException(e);
}
}
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.model.SharedStringsTable;
+import org.apache.poi.POIXMLException;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
* @return the value of the cell as a number
* @throws IllegalStateException if the cell type returned by {@link #getCellType()} is CELL_TYPE_STRING
* @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
+ * @see DataFormatter for turning this number into a string similar to that which Excel would render this number as.
*/
public double getNumericCellValue() {
int cellType = getCellType();
*/
public void setCellStyle(CellStyle style) {
if(style == null) {
- cell.unsetS();
+ if(cell.isSetS()) cell.unsetS();
} else {
XSSFCellStyle xStyle = (XSSFCellStyle)style;
xStyle.verifyBelongsToStylesSource(stylesSource);
* @return the value of the cell as a date
* @throws IllegalStateException if the cell type returned by {@link #getCellType()} is CELL_TYPE_STRING
* @exception NumberFormatException if the cell value isn't a parsable <code>double</code>.
+ * @see DataFormatter for formatting this date into a string similar to how excel does.
*/
public Date getDateCellValue() {
int cellType = getCellType();
*/
private static void checkBounds(int cellNum) {
if (cellNum > MAX_COLUMN_NUMBER) {
- throw new RuntimeException("You cannot have more than "+MAX_COLUMN_NUMBER+" columns " +
+ throw new POIXMLException("You cannot have more than "+MAX_COLUMN_NUMBER+" columns " +
"in a given row because Excel can't handle it");
} else if (cellNum < 0) {
- throw new RuntimeException("You cannot reference columns with an index of less then 0.");
+ throw new POIXMLException("You cannot reference columns with an index of less then 0.");
}
}
import org.apache.poi.xssf.usermodel.extensions.XSSFCellAlignment;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
-import org.apache.poi.xssf.usermodel.extensions.XSSFColor;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#getCellStyleAt(short)
* @see org.apache.poi.xssf.usermodel.XSSFCell#setCellStyle(org.apache.poi.ss.usermodel.CellStyle)
*/
-public class XSSFCellStyle implements CellStyle, Cloneable {
+public class XSSFCellStyle implements CellStyle {
private int cellXfId;
private StylesTable stylesSource;
* Creates an empty Cell Style
*/
public XSSFCellStyle(StylesTable stylesSource) {
- this.stylesSource = (StylesTable)stylesSource;
+ this.stylesSource = stylesSource;
// We need a new CTXf for the main styles
// TODO decide on a style ctxf
cellXf = CTXf.Factory.newInstance();
*/
public void cloneStyleFrom(CellStyle source) {
if(source instanceof XSSFCellStyle) {
- this.cloneStyleFrom((XSSFCellStyle)source);
+ this.cloneStyleFrom(source);
}
throw new IllegalArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle");
}
- public void cloneStyleFrom(XSSFCellStyle source) {
- throw new IllegalStateException("TODO");
- }
-
/**
* Get the type of horizontal alignment for the cell
*
* @see IndexedColors
*/
public short getBottomBorderColor() {
- XSSFColor clr = getBottomBorderRgbColor();
+ XSSFColor clr = getBottomBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
*
* @return the used color or <code>null</code> if not set
*/
- public XSSFColor getBottomBorderRgbColor() {
+ public XSSFColor getBottomBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
* @see IndexedColors
*/
public short getFillBackgroundColor() {
- XSSFColor clr = getFillBackgroundRgbColor();
+ XSSFColor clr = getFillBackgroundXSSFColor();
return clr == null ? IndexedColors.AUTOMATIC.getIndex() : (short)clr.getIndexed();
}
* Note - many cells are actually filled with a foreground
* fill, not a background fill - see {@link #getFillForegroundColor()}
* </p>
- * @see org.apache.poi.xssf.usermodel.extensions.XSSFColor#getRgb()
+ * @see org.apache.poi.xssf.usermodel.XSSFColor#getRgb()
* @return XSSFColor - fill color or <code>null</code> if not set
*/
- public XSSFColor getFillBackgroundRgbColor() {
+ public XSSFColor getFillBackgroundXSSFColor() {
if(!cellXf.getApplyFill()) return null;
int fillIndex = (int)cellXf.getFillId();
* @return fill color, default value is {@link IndexedColors.AUTOMATIC}
*/
public short getFillForegroundColor() {
- XSSFColor clr = getFillForegroundRgbColor();
+ XSSFColor clr = getFillForegroundXSSFColor();
return clr == null ? IndexedColors.AUTOMATIC.getIndex() : (short)clr.getIndexed();
}
*
* @return XSSFColor - fill color or <code>null</code> if not set
*/
- public XSSFColor getFillForegroundRgbColor() {
+ public XSSFColor getFillForegroundXSSFColor() {
if(!cellXf.getApplyFill()) return null;
int fillIndex = (int)cellXf.getFillId();
* @see IndexedColors
*/
public short getLeftBorderColor() {
- XSSFColor clr = getLeftBorderRgbColor();
+ XSSFColor clr = getLeftBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
* @return the index of the color definition or <code>null</code> if not set
* @see IndexedColors
*/
- public XSSFColor getLeftBorderRgbColor() {
+ public XSSFColor getLeftBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
* @see IndexedColors
*/
public short getRightBorderColor() {
- XSSFColor clr = getRightBorderRgbColor();
+ XSSFColor clr = getRightBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
/**
*
* @return the used color or <code>null</code> if not set
*/
- public XSSFColor getRightBorderRgbColor() {
+ public XSSFColor getRightBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
* @see IndexedColors
*/
public short getTopBorderColor() {
- XSSFColor clr = getTopBorderRgbColor();
+ XSSFColor clr = getTopBorderXSSFColor();
return clr == null ? IndexedColors.BLACK.getIndex() : (short)clr.getIndexed();
}
*
* @return the used color or <code>null</code> if not set
*/
- public XSSFColor getTopBorderRgbColor() {
+ public XSSFColor getTopBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId();
*
* @param border the type of border to use
*/
- public void setBorderTopEnum(BorderStyle border) {
+ public void setBorderTop(BorderStyle border) {
setBorderTop((short)border.ordinal());
}
* For example:
* <pre>
* cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
- * cs.setFillBackgroundRgbColor(new XSSFColor(java.awt.Color.RED));
+ * cs.setFillBackgroundXSSFColor(new XSSFColor(java.awt.Color.RED));
* </pre>
* optionally a Foreground and background fill can be applied:
* <i>Note: Ensure Foreground color is set prior to background</i>
* For example:
* <pre>
* cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
- * cs.setFillBackgroundRgbColor(IndexedColors.RED.getIndex());
+ * cs.setFillBackgroundXSSFColor(IndexedColors.RED.getIndex());
* </pre>
* optionally a Foreground and background fill can be applied:
* <i>Note: Ensure Foreground color is set prior to background</i>
* <br/>
* <i>Note: Ensure Foreground color is set prior to background color.</i>
* @param color the color to use
- * @see #setFillBackgroundColor(org.apache.poi.xssf.usermodel.extensions.XSSFColor) )
+ * @see #setFillBackgroundColor(org.apache.poi.xssf.usermodel.XSSFColor) )
*/
public void setFillForegroundColor(XSSFColor color) {
CTFill ct = getCTFill();
}
/**
- * Set whether the text should be wrapped
+ * Set whether the text should be wrapped.
+ * <p>
+ * Setting this flag to <code>true</code> make all content visible
+ * whithin a cell by displaying it on multiple lines
+ * </p>
*
* @param wrapped a boolean value indicating if the text in a cell should be line-wrapped within the cell.
*/
public XSSFColor getBorderColor(BorderSide side) {
switch(side){
case BOTTOM:
- return getBottomBorderRgbColor();
+ return getBottomBorderXSSFColor();
case RIGHT:
- return getRightBorderRgbColor();
+ return getRightBorderXSSFColor();
case TOP:
- return getTopBorderRgbColor();
+ return getTopBorderXSSFColor();
case LEFT:
- return getLeftBorderRgbColor();
+ return getLeftBorderXSSFColor();
default:
throw new IllegalArgumentException("Unknown border: " + side);
}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+==================================================================== */
+package org.apache.poi.xssf.usermodel;
+
+import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;
+
+/**
+ * Represents a color in SpreadsheetML
+ */
+public class XSSFColor {
+
+ private CTColor ctColor;
+
+ /**
+ * Create an instance of XSSFColor from the supplied XML bean
+ */
+ public XSSFColor(CTColor color) {
+ this.ctColor = color;
+ }
+
+ /**
+ * Create an new instance of XSSFColor
+ */
+ public XSSFColor() {
+ this.ctColor = CTColor.Factory.newInstance();
+ }
+
+ public XSSFColor(java.awt.Color clr) {
+ this();
+ ctColor.setRgb(new byte[]{(byte)clr.getRed(), (byte)clr.getGreen(), (byte)clr.getBlue()});
+ }
+
+ /**
+ * A boolean value indicating the ctColor is automatic and system ctColor dependent.
+ */
+ public boolean isAuto() {
+ return ctColor.getAuto();
+ }
+
+ /**
+ * A boolean value indicating the ctColor is automatic and system ctColor dependent.
+ */
+ public void setAuto(boolean auto) {
+ ctColor.setAuto(auto);
+ }
+
+ /**
+ * Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors.
+ */
+ public short getIndexed() {
+ return (short)ctColor.getIndexed();
+ }
+
+ /**
+ * Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors.
+ */
+ public void setIndexed(int indexed) {
+ ctColor.setIndexed(indexed);
+ }
+
+ /**
+ * Standard Alpha Red Green Blue ctColor value (ARGB).
+ */
+ public byte[] getRgb() {
+ return ctColor.getRgb();
+ }
+
+ /**
+ * Standard Alpha Red Green Blue ctColor value (ARGB).
+ */
+ public void setRgb(byte[] rgb) {
+ ctColor.setRgb(rgb);
+ }
+
+ /**
+ * Index into the <clrScheme> collection, referencing a particular <sysClr> or
+ * <srgbClr> value expressed in the Theme part.
+ */
+ public int getTheme() {
+ return (int)ctColor.getTheme();
+ }
+
+ /**
+ * Index into the <clrScheme> collection, referencing a particular <sysClr> or
+ * <srgbClr> value expressed in the Theme part.
+ */
+ public void setTheme(int theme) {
+ ctColor.setTheme(theme);
+ }
+
+ /**
+ * Specifies the tint value applied to the ctColor.
+ *
+ * <p>
+ * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final
+ * ctColor applied.
+ * </p>
+ * <p>
+ * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and
+ * 1.0 means 100% lighten. Also, 0.0 means no change.
+ * </p>
+ * <p>
+ * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where
+ * HLSMAX is currently 255.
+ * </p>
+ * Here are some examples of how to apply tint to ctColor:
+ * <blockquote>
+ * <pre>
+ * If (tint < 0)
+ * Lum\92 = Lum * (1.0 + tint)
+ *
+ * For example: Lum = 200; tint = -0.5; Darken 50%
+ * Lum\91 = 200 * (0.5) => 100
+ * For example: Lum = 200; tint = -1.0; Darken 100% (make black)
+ * Lum\91 = 200 * (1.0-1.0) => 0
+ * If (tint > 0)
+ * Lum\91 = Lum * (1.0-tint) + (HLSMAX \96 HLSMAX * (1.0-tint))
+ * For example: Lum = 100; tint = 0.75; Lighten 75%
+ *
+ * Lum\91 = 100 * (1-.75) + (HLSMAX \96 HLSMAX*(1-.75))
+ * = 100 * .25 + (255 \96 255 * .25)
+ * = 25 + (255 \96 63) = 25 + 192 = 217
+ * For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
+ * Lum\91 = 100 * (1-1) + (HLSMAX \96 HLSMAX*(1-1))
+ * = 100 * 0 + (255 \96 255 * 0)
+ * = 0 + (255 \96 0) = 255
+ * </pre>
+ * </blockquote>
+ *
+ * @return the tint value
+ */
+ public double getTint() {
+ return ctColor.getTint();
+ }
+
+ /**
+ * Specifies the tint value applied to the ctColor.
+ *
+ * <p>
+ * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final
+ * ctColor applied.
+ * </p>
+ * <p>
+ * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and
+ * 1.0 means 100% lighten. Also, 0.0 means no change.
+ * </p>
+ * <p>
+ * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where
+ * HLSMAX is currently 255.
+ * </p>
+ * Here are some examples of how to apply tint to ctColor:
+ * <blockquote>
+ * <pre>
+ * If (tint < 0)
+ * Lum\92 = Lum * (1.0 + tint)
+ *
+ * For example: Lum = 200; tint = -0.5; Darken 50%
+ * Lum\91 = 200 * (0.5) => 100
+ * For example: Lum = 200; tint = -1.0; Darken 100% (make black)
+ * Lum\91 = 200 * (1.0-1.0) => 0
+ * If (tint > 0)
+ * Lum\91 = Lum * (1.0-tint) + (HLSMAX \96 HLSMAX * (1.0-tint))
+ * For example: Lum = 100; tint = 0.75; Lighten 75%
+ *
+ * Lum\91 = 100 * (1-.75) + (HLSMAX \96 HLSMAX*(1-.75))
+ * = 100 * .25 + (255 \96 255 * .25)
+ * = 25 + (255 \96 63) = 25 + 192 = 217
+ * For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
+ * Lum\91 = 100 * (1-1) + (HLSMAX \96 HLSMAX*(1-1))
+ * = 100 * 0 + (255 \96 255 * 0)
+ * = 0 + (255 \96 0) = 255
+ * </pre>
+ * </blockquote>
+ *
+ * @param tint the tint value
+ */
+ public void setTint(double tint) {
+ ctColor.setTint(tint);
+ }
+
+ /**
+ * Returns the underlying XML bean
+ *
+ * @return the underlying XML bean
+ */
+ public CTColor getCTColor(){
+ return ctColor;
+ }
+
+ public int hashCode(){
+ return ctColor.toString().hashCode();
+ }
+
+ public boolean equals(Object o){
+ if(o == null || !(o instanceof XSSFColor)) return false;
+
+ XSSFColor cf = (XSSFColor)o;
+ return ctColor.toString().equals(cf.getCTColor().toString());
+ }
+
+}
package org.apache.poi.xssf.usermodel;
import org.apache.poi.ss.usermodel.*;
-import org.apache.poi.xssf.usermodel.extensions.XSSFColor;
import org.apache.poi.xssf.model.StylesTable;
+import org.apache.poi.POIXMLException;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
/**
*
* @return XSSFColor - rgb color to use
*/
- public XSSFColor getRgbColor() {
+ public XSSFColor getXSSFColor() {
CTColor ctColor = ctFont.sizeOfColorArray() == 0 ? null : ctFont.getColorArray(0);
return ctColor == null ? null : new XSSFColor(ctColor);
}
case STVerticalAlignRun.INT_SUPERSCRIPT:
return Font.SS_SUPER;
default:
- throw new RuntimeException("Wrong offset value " + val);
+ throw new POIXMLException("Wrong offset value " + val);
}
} else
return Font.SS_NONE;
charsetProperty.setVal(FontCharset.DEFAULT.getValue());
break;
default:
- throw new RuntimeException("Attention: an attempt to set a type of unknow charset and charset");
+ throw new POIXMLException("Attention: an attempt to set a type of unknow charset and charset");
}
}
ctColor.setIndexed(color);
}
}
+
+ /**
+ * set the color for the font in Standard Alpha Red Green Blue color value
+ *
+ * @param color - color to use
+ */
public void setColor(XSSFColor color) {
if(color == null) ctFont.setColorArray(null);
- else ctFont.setColorArray(new CTColor[]{color.getCTColor()});
+ else {
+ CTColor ctColor = ctFont.sizeOfColorArray() == 0 ? ctFont.addNewColor() : ctFont.getColorArray(0);
+ ctColor.setRgb(color.getRgb());
+ }
}
/**
setFontHeight(height);
}
- /**
- * set the color for the font in Standard Alpha Red Green Blue color value
- *
- * @param color - color to use
- */
- public void setRgbColor(XSSFColor color) {
- CTColor ctColor = ctFont.sizeOfColorArray() == 0 ? ctFont.addNewColor() : ctFont.getColorArray(0);
- ctColor.setRgb(color.getRgb());
- }
-
/**
* set the theme color for the font to use
*
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.util.AreaReference;
+import org.apache.poi.util.POILogger;
+import org.apache.poi.util.POILogFactory;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
/**
* @author Yegor Kozlov
*/
public class XSSFName implements Name {
+ private static POILogger logger = POILogFactory.getLogger(XSSFWorkbook.class);
/**
* A built-in defined name that specifies the workbook's print area
* @throws IllegalArgumentException if the specified reference is unparsable
*/
public void setReference(String ref) {
- String normalizedRef = AreaReference.isContiguous(ref) ? new AreaReference(ref).formatAsString() : ref;
- ctName.setStringValue(normalizedRef);
+ try {
+ ref = AreaReference.isContiguous(ref) ? new AreaReference(ref).formatAsString() : ref;
+ } catch (IllegalArgumentException e){
+ logger.log(POILogger.WARN, "failed to parse cell reference. Setting raw value");
+ }
+ ctName.setStringValue(ref);
}
/**
package org.apache.poi.xssf.usermodel;
import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.POIXMLException;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
* @param scale the scale to use
*/
public void setScale(short scale) {
- if (scale < 10 || scale > 400) throw new RuntimeException("Scale value not accepted: you must choose a value between 10 and 400.");
+ if (scale < 10 || scale > 400) throw new POIXMLException("Scale value not accepted: you must choose a value between 10 and 400.");
pageSetup.setScale(scale);
}
}
/**
- * Sdds a merged region of cells (hence those cells form one)
+ * Adds a merged region of cells (hence those cells form one).
*
* @param cra (rowfrom/colfrom-rowto/colto) to merge
* @return index of this region
* @param leftmostColumn Left column visible in right pane.
*/
public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) {
- this.createFreezePane(colSplit, rowSplit);
- this.showInPane((short)topRow, (short)leftmostColumn);
+ CTPane pane = getPane();
+ if (colSplit > 0) pane.setXSplit(colSplit);
+ if (rowSplit > 0) pane.setYSplit(rowSplit);
+ pane.setState(STPaneState.FROZEN);
+ if (rowSplit == 0) {
+ pane.setTopLeftCell(new CellReference(0, topRow).formatAsString());
+ pane.setActivePane(STPane.TOP_RIGHT);
+ } else if (colSplit == 0) {
+ pane.setTopLeftCell(new CellReference(leftmostColumn, 64).formatAsString());
+ pane.setActivePane(STPane.BOTTOM_LEFT);
+ } else {
+ pane.setTopLeftCell(new CellReference(leftmostColumn, topRow).formatAsString());
+ pane.setActivePane(STPane.BOTTOM_RIGHT);
+ }
+
+ CTSheetView ctView = getDefaultSheetView();
+ ctView.setSelectionArray(null);
+ CTSelection sel = ctView.addNewSelection();
+ sel.setPane(pane.getActivePane());
}
/**
* @param rowSplit Vertical position of split.
*/
public void createFreezePane(int colSplit, int rowSplit) {
- getPane().setXSplit(colSplit);
- getPane().setYSplit(rowSplit);
- // make bottomRight default active pane
- getPane().setActivePane(STPane.BOTTOM_RIGHT);
+ createFreezePane( colSplit, rowSplit, colSplit, rowSplit );
}
/**
return breaks;
}
- protected CTPageBreak getSheetTypeColumnBreaks() {
+ private CTPageBreak getSheetTypeColumnBreaks() {
if (worksheet.getColBreaks() == null) {
worksheet.setColBreaks(CTPageBreak.Factory.newInstance());
}
* Note, this value is different from {@link #getColumnWidth(int)}. The latter is always greater and includes
* 4 pixels of margin padding (two on each side), plus 1 pixel padding for the gridlines.
* </p>
- * @return default column width
+ * @return column width, default value is 8
*/
public int getDefaultColumnWidth() {
- CTSheetFormatPr pr = getSheetTypeSheetFormatPr();
- return (int)pr.getBaseColWidth();
+ CTSheetFormatPr pr = worksheet.getSheetFormatPr();
+ return pr == null ? 8 : (int)pr.getBaseColWidth();
}
/**
* @return default row height
*/
public short getDefaultRowHeight() {
- return (short) (getSheetTypeSheetFormatPr().getDefaultRowHeight() * 20);
+ return (short)(getDefaultRowHeightInPoints() * 20);
}
/**
* @return default row height in points
*/
public float getDefaultRowHeightInPoints() {
- return (float)getSheetTypeSheetFormatPr().getDefaultRowHeight();
+ CTSheetFormatPr pr = worksheet.getSheetFormatPr();
+ return (float)(pr == null ? 0 : pr.getDefaultRowHeight());
}
- protected CTSheetFormatPr getSheetTypeSheetFormatPr() {
+ private CTSheetFormatPr getSheetTypeSheetFormatPr() {
return worksheet.isSetSheetFormatPr() ?
worksheet.getSheetFormatPr() :
worksheet.addNewSheetFormatPr();
return psSetup.getFitToPage();
}
- protected CTSheetPr getSheetTypeSheetPr() {
+ private CTSheetPr getSheetTypeSheetPr() {
if (worksheet.getSheetPr() == null) {
worksheet.setSheetPr(CTSheetPr.Factory.newInstance());
}
return worksheet.getSheetPr();
}
- protected CTHeaderFooter getSheetTypeHeaderFooter() {
+ private CTHeaderFooter getSheetTypeHeaderFooter() {
if (worksheet.getHeaderFooter() == null) {
worksheet.setHeaderFooter(CTHeaderFooter.Factory.newInstance());
}
}
+ /**
+ * Determine whether printed output for this sheet will be horizontally centered.
+ */
public boolean getHorizontallyCenter() {
- return getSheetTypePrintOptions().getHorizontalCentered();
- }
-
- protected CTPrintOptions getSheetTypePrintOptions() {
- if (worksheet.getPrintOptions() == null) {
- worksheet.setPrintOptions(CTPrintOptions.Factory.newInstance());
- }
- return worksheet.getPrintOptions();
+ CTPrintOptions opts = worksheet.getPrintOptions();
+ return opts != null && opts.getHorizontalCentered();
}
public int getLastRowNum() {
return hyperlinks.size();
}
+ /**
+ * Returns the information regarding the currently configured pane (split or freeze).
+ *
+ * @return null if no pane configured, or the pane information.
+ */
public PaneInformation getPaneInformation() {
- // TODO Auto-generated method stub
- return null;
+ CTPane pane = getPane();
+ CellReference cellRef = pane.isSetTopLeftCell() ? new CellReference(pane.getTopLeftCell()) : null;
+ return new PaneInformation((short)pane.getXSplit(), (short)pane.getYSplit(),
+ (short)(cellRef == null ? 0 : cellRef.getRow()),(cellRef == null ? 0 : cellRef.getCol()),
+ (byte)pane.getActivePane().intValue(), pane.getState() == STPaneState.FROZEN);
}
/**
* @return whether printed output for this sheet will be vertically centered.
*/
public boolean getVerticallyCenter() {
- return getSheetTypePrintOptions().getVerticalCentered();
+ CTPrintOptions opts = worksheet.getPrintOptions();
+ return opts != null && opts.getVerticalCentered();
}
/**
}
/**
- * Gets the flag indicating whether this sheet should display gridlines.
+ * Gets the flag indicating whether this sheet displays the lines
+ * between rows and columns to make editing and reading easier.
*
- * @return <code>true</code> if this sheet should display gridlines.
+ * @return <code>true</code> if this sheet displays gridlines.
+ * @see #isPrintGridlines() to check if printing of gridlines is turned on or off
*/
public boolean isDisplayGridlines() {
return getSheetTypeSheetView().getShowGridLines();
}
+ /**
+ * Sets the flag indicating whether this sheet should display the lines
+ * between rows and columns to make editing and reading easier.
+ * To turn printing of gridlines use {@link #setPrintGridlines(boolean)}
+ *
+ *
+ * @param show <code>true</code> if this sheet should display gridlines.
+ * @see #setPrintGridlines(boolean)
+ */
+ public void setDisplayGridlines(boolean show) {
+ getSheetTypeSheetView().setShowGridLines(show);
+ }
+
/**
* Gets the flag indicating whether this sheet should display row and column headings.
+ * <p>
+ * Row heading are the row numbers to the side of the sheet
+ * </p>
+ * <p>
+ * Column heading are the letters or numbers that appear above the columns of the sheet
+ * </p>
*
* @return <code>true</code> if this sheet should display row and column headings.
*/
return getSheetTypeSheetView().getShowRowColHeaders();
}
- public boolean isGridsPrinted() {
- return isPrintGridlines();
+ /**
+ * Sets the flag indicating whether this sheet should display row and column headings.
+ * <p>
+ * Row heading are the row numbers to the side of the sheet
+ * </p>
+ * <p>
+ * Column heading are the letters or numbers that appear above the columns of the sheet
+ * </p>
+ *
+ * @param show <code>true</code> if this sheet should display row and column headings.
+ */
+ public void setDisplayRowColHeadings(boolean show) {
+ getSheetTypeSheetView().setShowRowColHeaders(show);
}
+ /**
+ * Returns whether gridlines are printed.
+ *
+ * @return whether gridlines are printed
+ */
public boolean isPrintGridlines() {
- return getSheetTypePrintOptions().getGridLines();
+ CTPrintOptions opts = worksheet.getPrintOptions();
+ return opts != null && opts.getGridLines();
+ }
+
+ /**
+ * Turns on or off the printing of gridlines.
+ *
+ * @param value boolean to turn on or off the printing of gridlines
+ */
+ public void setPrintGridlines(boolean value) {
+ CTPrintOptions opts = worksheet.isSetPrintOptions() ?
+ worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
+ opts.setGridLines(value);
}
/**
}
}
+ /**
+ * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not
+ * be the third row if say for instance the second row is undefined.
+ * Call getRowNum() on each row if you care which one it is.
+ */
public Iterator<Row> rowIterator() {
return rows.values().iterator();
}
return rowIterator();
}
- public void setAlternativeExpression(boolean b) {
- // TODO Auto-generated method stub
-
- }
-
- public void setAlternativeFormula(boolean b) {
- // TODO Auto-generated method stub
-
- }
-
/**
* Flag indicating whether the sheet displays Automatic Page Breaks.
*
psSetup.setAutoPageBreaks(value);
}
+ /**
+ * Sets a page break at the indicated column
+ *
+ * @param column the column to break
+ */
public void setColumnBreak(short column) {
if (! isColumnBroken(column)) {
CTBreak brk = getSheetTypeColumnBreaks().addNewBrk();
}
+ public void setRowGroupCollapsed(int row, boolean collapse) {
+ // TODO Auto-generated method stub
+
+ }
+
/**
* Get the visibility state for a given column.
*
getSheetTypeSheetView().setShowFormulas(show);
}
- protected CTSheetView getSheetTypeSheetView() {
+ private CTSheetView getSheetTypeSheetView() {
if (getDefaultSheetView() == null) {
getSheetTypeSheetViews().setSheetViewArray(0, CTSheetView.Factory.newInstance());
}
return getDefaultSheetView();
}
- /**
- * Sets the flag indicating whether this sheet should display gridlines.
- *
- * @param show <code>true</code> if this sheet should display gridlines.
- */
- public void setDisplayGridlines(boolean show) {
- getSheetTypeSheetView().setShowGridLines(show);
- }
-
- /**
- * Sets the flag indicating whether this sheet should display row and column headings.
- *
- * @param show <code>true</code> if this sheet should display row and column headings.
- */
- public void setDisplayRowColHeadings(boolean show) {
- getSheetTypeSheetView().setShowRowColHeaders(show);
- }
-
/**
* Flag indicating whether the Fit to Page print option is enabled.
*
getSheetTypePageSetUpPr().setFitToPage(b);
}
- public void setGridsPrinted(boolean value) {
- setPrintGridlines(value);
- }
-
/**
* Center on page horizontally when printing.
*
* @param value whether to center on page horizontally when printing.
*/
public void setHorizontallyCenter(boolean value) {
- getSheetTypePrintOptions().setHorizontalCentered(value);
- }
-
- public void setPrintGridlines(boolean newPrintGridlines) {
- getSheetTypePrintOptions().setGridLines(newPrintGridlines);
- }
-
- public void setRowGroupCollapsed(int row, boolean collapse) {
- // TODO Auto-generated method stub
-
+ CTPrintOptions opts = worksheet.isSetPrintOptions() ?
+ worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
+ opts.setHorizontalCentered(value);
}
+ /**
+ * Whether the output is vertically centered on the page.
+ *
+ * @param value true to vertically center, false otherwise.
+ */
public void setVerticallyCenter(boolean value) {
- getSheetTypePrintOptions().setVerticalCentered(value);
+ CTPrintOptions opts = worksheet.isSetPrintOptions() ?
+ worksheet.getPrintOptions() : worksheet.addNewPrintOptions();
+ opts.setVerticalCentered(value);
}
/**
* Current view can be Normal, Page Layout, or Page Break Preview.
*
* @param scale window zoom magnification
+ * @throws IllegalArgumentException if scale is invalid
*/
public void setZoom(int scale) {
+ if(scale < 10 || scale > 400) throw new IllegalArgumentException("Valid scale values range from 10 to 400");
getSheetTypeSheetView().setZoomScale(scale);
}
- /**
- * Zoom magnification to use when in normal view, representing percent values.
- * Valid values range from 10 to 400. Horizontal & Vertical scale together.
- *
- * For example:
- * <pre>
- * 10 - 10%
- * 20 - 20%
- * \85
- * 100 - 100%
- * \85
- * 400 - 400%
- * </pre>
- *
- * Applies for worksheet sheet type only; zero implies the automatic setting.
- *
- * @param scale window zoom magnification
- */
- public void setZoomNormal(int scale) {
- getSheetTypeSheetView().setZoomScaleNormal(scale);
- }
-
- /**
- * Zoom magnification to use when in page layout view, representing percent values.
- * Valid values range from 10 to 400. Horizontal & Vertical scale together.
- *
- * For example:
- * <pre>
- * 10 - 10%
- * 20 - 20%
- * \85
- * 100 - 100%
- * \85
- * 400 - 400%
- * </pre>
- *
- * Applies for worksheet sheet type only; zero implies the automatic setting.
- *
- * @param scale
- */
- public void setZoomPageLayoutView(int scale) {
- getSheetTypeSheetView().setZoomScalePageLayoutView(scale);
- }
-
- /**
- * Zoom magnification to use when in page break preview, representing percent values.
- * Valid values range from 10 to 400. Horizontal & Vertical scale together.
- *
- * For example:
- * <pre>
- * 10 - 10%
- * 20 - 20%
- * \85
- * 100 - 100%
- * \85
- * 400 - 400%
- * </pre>
- *
- * Applies for worksheet only; zero implies the automatic setting.
- *
- * @param scale
- */
- public void setZoomSheetLayoutView(int scale) {
- getSheetTypeSheetView().setZoomScaleSheetLayoutView(scale);
- }
-
/**
* Shifts rows between startRow and endRow n number of rows.
* If you use a negative number, it will shift rows up.
* Additionally shifts merged regions that are completely defined in these
* rows (ie. merged 2 cells on a row to be shifted).
* <p>
- * TODO Might want to add bounds checking here
* @param startRow the row to start shifting
* @param endRow the row to end shifting
* @param n the number of rows to shift
}
public void ungroupColumn(short fromColumn, short toColumn) {
- CTCols cols=worksheet.getColsArray(0);
- for(int index=fromColumn;index<=toColumn;index++){
- CTCol col=columnHelper.getColumn(index, false);
- if(col!=null){
- short outlineLevel=col.getOutlineLevel();
- col.setOutlineLevel((short)(outlineLevel-1));
- index=(int)col.getMax();
-
- if(col.getOutlineLevel()<=0){
- int colIndex=columnHelper.getIndexOfColumn(cols,col);
+ CTCols cols = worksheet.getColsArray(0);
+ for (int index = fromColumn; index <= toColumn; index++) {
+ CTCol col = columnHelper.getColumn(index, false);
+ if (col != null) {
+ short outlineLevel = col.getOutlineLevel();
+ col.setOutlineLevel((short) (outlineLevel - 1));
+ index = (int) col.getMax();
+
+ if (col.getOutlineLevel() <= 0) {
+ int colIndex = columnHelper.getIndexOfColumn(cols, col);
worksheet.getColsArray(0).removeCol(colIndex);
}
}
}
- worksheet.setColsArray(0,cols);
+ worksheet.setColsArray(0, cols);
setSheetFormatPrOutlineLevelCol();
}
public void ungroupRow(int fromRow, int toRow) {
- for(int i=fromRow;i<=toRow;i++){
- XSSFRow xrow=getRow(i-1);
- if(xrow!=null){
- CTRow ctrow=xrow.getCTRow();
- short outlinelevel=ctrow.getOutlineLevel();
- ctrow.setOutlineLevel((short)(outlinelevel-1));
+ for (int i = fromRow; i <= toRow; i++) {
+ XSSFRow xrow = getRow(i - 1);
+ if (xrow != null) {
+ CTRow ctrow = xrow.getCTRow();
+ short outlinelevel = ctrow.getOutlineLevel();
+ ctrow.setOutlineLevel((short) (outlinelevel - 1));
//remove a row only if the row has no cell and if the outline level is 0
- if(ctrow.getOutlineLevel()==0 && xrow.getFirstCellNum()==-1){
+ if (ctrow.getOutlineLevel() == 0 && xrow.getFirstCellNum() == -1) {
removeRow(xrow);
}
}
* Returns the sheet's comments object if there is one,
* or null if not
*/
- protected CommentsTable getCommentsSourceIfExists() {
+ protected CommentsTable getCommentsTable() {
return sheetComments;
}
}
}
- // Load individual sheets. The order of sheets is defined by the order of CTSheet beans in the workbook
+ // Load individual sheets. The order of sheets is defined by the order of CTSheet elements in the workbook
sheets = new ArrayList<XSSFSheet>(shIdMap.size());
for (CTSheet ctSheet : this.workbook.getSheets().getSheetArray()) {
XSSFSheet sh = shIdMap.get(ctSheet.getId());
// Process the named ranges
namedRanges = new ArrayList<XSSFName>();
- if(workbook.getDefinedNames() != null) {
+ if(workbook.isSetDefinedNames()) {
for(CTDefinedName ctName : workbook.getDefinedNames().getDefinedNameArray()) {
namedRanges.add(new XSSFName(ctName, this));
}
* @return the new XSSFCellStyle object
*/
public XSSFCellStyle createCellStyle() {
- CTXf xf=CTXf.Factory.newInstance();
- xf.setNumFmtId(0);
- xf.setFontId(0);
- xf.setFillId(0);
- xf.setBorderId(0);
- xf.setXfId(0);
- int xfSize=(stylesSource)._getStyleXfsSize();
- int indexXf=(stylesSource).putCellXf(xf);
- XSSFCellStyle style = new XSSFCellStyle(indexXf-1, xfSize-1, stylesSource);
- return style;
+ return stylesSource.createCellStyle();
}
/**
*/
public XSSFSheet createSheet(String sheetname) {
if (containsSheet( sheetname, sheets.size() ))
- throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
+ throw new IllegalArgumentException( "The workbook already contains a sheet of this name");
CTSheet sheet = addSheet(sheetname);
* Finds a font that matches the one with the supplied attributes
*/
public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
- short fontNum = getNumberOfFonts();
- for (short i = 0; i < fontNum; i++) {
- XSSFFont xssfFont = getFontAt(i);
-
- if ( (xssfFont.getBold() == (boldWeight == XSSFFont.BOLDWEIGHT_BOLD))
- && xssfFont.getColor() == color
- && xssfFont.getFontHeightInPoints() == fontHeight
- && xssfFont.getFontName().equals(name)
- && xssfFont.getItalic() == italic
- && xssfFont.getStrikeout() == strikeout
- && xssfFont.getTypeOffset() == typeOffset
- && xssfFont.getUnderline() == underline)
- {
- return xssfFont;
- }
- }
- return null;
+ return stylesSource.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline);
}
/**
* @return number of fonts
*/
public short getNumberOfFonts() {
- return (short)(stylesSource).getNumberOfFonts();
+ return (short)stylesSource.getFonts().size();
}
/**
* @return number of worksheets
*/
public int getNumberOfSheets() {
- return this.sheets.size();
+ return sheets.size();
}
/**
* @return XSSFSheet with the name provided or <code>null</code> if it does not exist
*/
public XSSFSheet getSheet(String name) {
- CTSheet[] ctSheets = this.workbook.getSheets().getSheetArray();
- for (int i = 0 ; i < ctSheets.length ; ++i) {
- if (name.equalsIgnoreCase(ctSheets[i].getName())) {
- return sheets.get(i);
+ for (XSSFSheet sheet : sheets) {
+ if (name.equalsIgnoreCase(sheet.getSheetName())) {
+ return sheet;
}
}
return null;
* @return index of the sheet (0 based) or <tt>-1</tt if not found
*/
public int getSheetIndex(String name) {
- CTSheet[] sheets = this.workbook.getSheets().getSheetArray();
- for (int i = 0 ; i < sheets.length ; ++i) {
- if (name.equalsIgnoreCase(sheets[i].getName())) {
+ for (int i = 0 ; i < sheets.size() ; ++i) {
+ XSSFSheet sheet = sheets.get(i);
+ if (name.equalsIgnoreCase(sheet.getSheetName())) {
return i;
}
}
*/
public int getSheetIndex(Sheet sheet) {
int idx = 0;
- for(XSSFSheet sh : this){
+ for(XSSFSheet sh : sheets){
if(sh == sheet) return idx;
idx++;
}
*/
public String getSheetName(int sheetIx) {
validateSheetIndex(sheetIx);
- return this.workbook.getSheets().getSheetArray(sheetIx).getName();
+ return sheets.get(sheetIx).getSheetName();
}
/**
* Generates a NameRecord to represent a built-in region
*
* @return a new NameRecord
+ * @throws IllegalArgumentException if sheetNumber is invalid
+ * @throws POIXMLException if such a name already exists in the workbook
*/
private XSSFName createBuiltInName(String builtInName, int sheetNumber) {
- if (sheetNumber < 0 || sheetNumber + 1 > Short.MAX_VALUE) {
- throw new IllegalArgumentException("Sheet number [" + sheetNumber + "]is not valid ");
- }
+ validateSheetIndex(sheetNumber);
CTDefinedNames names = workbook.getDefinedNames() == null ? workbook.addNewDefinedNames() : workbook.getDefinedNames();
CTDefinedName nameRecord = names.addNewDefinedName();
XSSFName name = new XSSFName(nameRecord, this);
for (XSSFName nr : namedRanges) {
if (nr.equals(name))
- throw new RuntimeException("Builtin (" + builtInName
+ throw new POIXMLException("Builtin (" + builtInName
+ ") already exists for sheet (" + sheetNumber + ")");
}
* We only set one sheet as selected for compatibility with HSSF.
*/
public void setSelectedTab(short index) {
- for (int i = 0 ; i < this.sheets.size() ; ++i) {
- XSSFSheet sheet = this.sheets.get(i);
+ for (int i = 0 ; i < sheets.size() ; ++i) {
+ XSSFSheet sheet = sheets.get(i);
sheet.setSelected(i == index);
}
}
validateSheetName(name);
if (containsSheet(name, sheet ))
throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
- this.workbook.getSheets().getSheetArray(sheet).setName(name);
+ workbook.getSheets().getSheetArray(sheet).setName(name);
}
/**
int idx = getSheetIndex(sheetname);
sheets.add(pos, sheets.remove(idx));
// Reorder CTSheets
- XmlObject cts = this.workbook.getSheets().getSheetArray(idx).copy();
- this.workbook.getSheets().removeSheet(idx);
- CTSheet newcts = this.workbook.getSheets().insertNewSheet(pos);
+ XmlObject cts = workbook.getSheets().getSheetArray(idx).copy();
+ workbook.getSheets().removeSheet(idx);
+ CTSheet newcts = workbook.getSheets().insertNewSheet(pos);
newcts.set(cts);
}
}
return embedds;
}
+
+ /**
+ * Check whether a sheet is hidden.
+ * Note that a sheet could instead be set to be very hidden, which is different
+ * ({@link #isSheetVeryHidden(int)})
+ * @param sheetIx Number
+ * @return True if sheet is hidden
+ * @throws IllegalArgumentException if sheetIx is invalid
+ */
+ public boolean isSheetHidden(int sheetIx) {
+ validateSheetIndex(sheetIx);
+ CTSheet ctSheet = sheets.get(sheetIx).sheet;
+ return ctSheet.getState() == STSheetState.HIDDEN;
+ }
+
+ /**
+ * Check whether a sheet is very hidden.
+ * This is different from the normal hidden status ({@link #isSheetHidden(int)})
+ * @param sheetIx Number
+ * @return True if sheet is very hidden
+ * @throws IllegalArgumentException if sheetIx is invalid
+ */
+ public boolean isSheetVeryHidden(int sheetIx) {
+ validateSheetIndex(sheetIx);
+ CTSheet ctSheet = sheets.get(sheetIx).sheet;
+ return ctSheet.getState() == STSheetState.VERY_HIDDEN;
+ }
+
+ /**
+ * Hide or unhide a sheet
+ *
+ * @param sheetIx The sheet index
+ * @param hidden True to mark the sheet as hidden, false otherwise
+ * @throws IllegalArgumentException if sheetIx is invalid
+ */
+ public void setSheetHidden(int sheetIx, boolean hidden) {
+ validateSheetIndex(sheetIx);
+ CTSheet ctSheet = sheets.get(sheetIx).sheet;
+ ctSheet.setState(hidden ? STSheetState.HIDDEN : STSheetState.VISIBLE);
+ }
+
+ /**
+ * Hide or unhide a sheet.
+ * <pre>
+ * 0 = not hidden
+ * 1 = hidden
+ * 2 = very hidden.
+ * </pre>
+ *
+ * @param sheetIx The sheet number
+ * @param hidden 0 for not hidden, 1 for hidden, 2 for very hidden
+ * @throws IllegalArgumentException if sheetIx is invalid
+ */
+ public void setSheetHidden(int sheetIx, int hidden) {
+ validateSheetIndex(sheetIx);
+ CTSheet ctSheet = sheets.get(sheetIx).sheet;
+ ctSheet.setState(STSheetState.Enum.forInt(hidden));
+ }
+
}
import org.apache.poi.ss.usermodel.BorderStyle;
+import org.apache.poi.xssf.usermodel.XSSFColor;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPatternFill;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType;
+import org.apache.poi.xssf.usermodel.XSSFColor;
/**
* This element specifies fill formatting.
+++ /dev/null
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.xssf.usermodel.extensions;
-
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;
-
-/**
- * Represents a color in SpreadsheetML
- */
-public class XSSFColor {
-
- private CTColor ctColor;
-
- /**
- * Create an instance of XSSFColor from the supplied XML bean
- */
- public XSSFColor(CTColor color) {
- this.ctColor = color;
- }
-
- /**
- * Create an new instance of XSSFColor
- */
- public XSSFColor() {
- this.ctColor = CTColor.Factory.newInstance();
- }
-
- public XSSFColor(java.awt.Color clr) {
- this();
- ctColor.setRgb(new byte[]{(byte)clr.getRed(), (byte)clr.getGreen(), (byte)clr.getBlue()});
- }
-
- /**
- * A boolean value indicating the ctColor is automatic and system ctColor dependent.
- */
- public boolean isAuto() {
- return ctColor.getAuto();
- }
-
- /**
- * A boolean value indicating the ctColor is automatic and system ctColor dependent.
- */
- public void setAuto(boolean auto) {
- ctColor.setAuto(auto);
- }
-
- /**
- * Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors.
- */
- public short getIndexed() {
- return (short)ctColor.getIndexed();
- }
-
- /**
- * Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors.
- */
- public void setIndexed(int indexed) {
- ctColor.setIndexed(indexed);
- }
-
- /**
- * Standard Alpha Red Green Blue ctColor value (ARGB).
- */
- public byte[] getRgb() {
- return ctColor.getRgb();
- }
-
- /**
- * Standard Alpha Red Green Blue ctColor value (ARGB).
- */
- public void setRgb(byte[] rgb) {
- ctColor.setRgb(rgb);
- }
-
- /**
- * Index into the <clrScheme> collection, referencing a particular <sysClr> or
- * <srgbClr> value expressed in the Theme part.
- */
- public int getTheme() {
- return (int)ctColor.getTheme();
- }
-
- /**
- * Index into the <clrScheme> collection, referencing a particular <sysClr> or
- * <srgbClr> value expressed in the Theme part.
- */
- public void setTheme(int theme) {
- ctColor.setTheme(theme);
- }
-
- /**
- * Specifies the tint value applied to the ctColor.
- *
- * <p>
- * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final
- * ctColor applied.
- * </p>
- * <p>
- * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and
- * 1.0 means 100% lighten. Also, 0.0 means no change.
- * </p>
- * <p>
- * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where
- * HLSMAX is currently 255.
- * </p>
- * Here are some examples of how to apply tint to ctColor:
- * <blockquote>
- * <pre>
- * If (tint < 0)
- * Lum\92 = Lum * (1.0 + tint)
- *
- * For example: Lum = 200; tint = -0.5; Darken 50%
- * Lum\91 = 200 * (0.5) => 100
- * For example: Lum = 200; tint = -1.0; Darken 100% (make black)
- * Lum\91 = 200 * (1.0-1.0) => 0
- * If (tint > 0)
- * Lum\91 = Lum * (1.0-tint) + (HLSMAX \96 HLSMAX * (1.0-tint))
- * For example: Lum = 100; tint = 0.75; Lighten 75%
- *
- * Lum\91 = 100 * (1-.75) + (HLSMAX \96 HLSMAX*(1-.75))
- * = 100 * .25 + (255 \96 255 * .25)
- * = 25 + (255 \96 63) = 25 + 192 = 217
- * For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
- * Lum\91 = 100 * (1-1) + (HLSMAX \96 HLSMAX*(1-1))
- * = 100 * 0 + (255 \96 255 * 0)
- * = 0 + (255 \96 0) = 255
- * </pre>
- * </blockquote>
- *
- * @return the tint value
- */
- public double getTint() {
- return ctColor.getTint();
- }
-
- /**
- * Specifies the tint value applied to the ctColor.
- *
- * <p>
- * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final
- * ctColor applied.
- * </p>
- * <p>
- * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and
- * 1.0 means 100% lighten. Also, 0.0 means no change.
- * </p>
- * <p>
- * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where
- * HLSMAX is currently 255.
- * </p>
- * Here are some examples of how to apply tint to ctColor:
- * <blockquote>
- * <pre>
- * If (tint < 0)
- * Lum\92 = Lum * (1.0 + tint)
- *
- * For example: Lum = 200; tint = -0.5; Darken 50%
- * Lum\91 = 200 * (0.5) => 100
- * For example: Lum = 200; tint = -1.0; Darken 100% (make black)
- * Lum\91 = 200 * (1.0-1.0) => 0
- * If (tint > 0)
- * Lum\91 = Lum * (1.0-tint) + (HLSMAX \96 HLSMAX * (1.0-tint))
- * For example: Lum = 100; tint = 0.75; Lighten 75%
- *
- * Lum\91 = 100 * (1-.75) + (HLSMAX \96 HLSMAX*(1-.75))
- * = 100 * .25 + (255 \96 255 * .25)
- * = 25 + (255 \96 63) = 25 + 192 = 217
- * For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
- * Lum\91 = 100 * (1-1) + (HLSMAX \96 HLSMAX*(1-1))
- * = 100 * 0 + (255 \96 255 * 0)
- * = 0 + (255 \96 0) = 255
- * </pre>
- * </blockquote>
- *
- * @param tint the tint value
- */
- public void setTint(double tint) {
- ctColor.setTint(tint);
- }
-
- /**
- * Returns the underlying XML bean
- *
- * @return the underlying XML bean
- */
- public CTColor getCTColor(){
- return ctColor;
- }
-
- public int hashCode(){
- return ctColor.toString().hashCode();
- }
-
- public boolean equals(Object o){
- if(!(o instanceof XSSFColor)) return false;
-
- XSSFColor cf = (XSSFColor)o;
- return ctColor.toString().equals(cf.getCTColor().toString());
- }
-
-}
XSSFReader r = new XSSFReader(pkg);
- assertEquals(3, r.getStylesTable()._getFontsSize());
+ assertEquals(3, r.getStylesTable().getFonts().size());
assertEquals(0, r.getStylesTable()._getNumberFormatSize());
}
package org.apache.poi.xssf.model;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
StylesTable st = new StylesTable();
// Check defaults
- assertNotNull(st._getRawStylesheet());
+ assertNotNull(st.getCTStylesheet());
assertEquals(1, st._getXfsSize());
assertEquals(1, st._getStyleXfsSize());
assertEquals(0, st._getNumberFormatSize());
XSSFWorkbook wb = new XSSFWorkbook();
StylesTable st = wb.getStylesSource();
- assertNotNull(st._getRawStylesheet());
+ assertNotNull(st.getCTStylesheet());
assertEquals(1, st._getXfsSize());
assertEquals(1, st._getStyleXfsSize());
assertEquals(0, st._getNumberFormatSize());
st = XSSFTestDataSamples.writeOutAndReadBack(wb).getStylesSource();
- assertNotNull(st._getRawStylesheet());
+ assertNotNull(st.getCTStylesheet());
assertEquals(1, st._getXfsSize());
assertEquals(1, st._getStyleXfsSize());
assertEquals(0, st._getNumberFormatSize());
}
public void doTestExisting(StylesTable st) throws Exception {
// Check contents
- assertNotNull(st._getRawStylesheet());
+ assertNotNull(st.getCTStylesheet());
assertEquals(11, st._getXfsSize());
assertEquals(1, st._getStyleXfsSize());
assertEquals(8, st._getNumberFormatSize());
- assertEquals(2, st._getFontsSize());
- assertEquals(2, st._getFillsSize());
- assertEquals(1, st._getBordersSize());
+ assertEquals(2, st.getFonts().size());
+ assertEquals(2, st.getFills().size());
+ assertEquals(1, st.getBorders().size());
assertEquals("yyyy/mm/dd", st.getNumberFormatAt(165));
assertEquals("yy/mm/dd", st.getNumberFormatAt(167));
XSSFWorkbook wb = new XSSFWorkbook();
StylesTable st = wb.getStylesSource();
- assertNotNull(st._getRawStylesheet());
+ assertNotNull(st.getCTStylesheet());
assertEquals(1, st._getXfsSize());
assertEquals(1, st._getStyleXfsSize());
assertEquals(0, st._getNumberFormatSize());
// Save and re-load
st = XSSFTestDataSamples.writeOutAndReadBack(wb).getStylesSource();
- assertNotNull(st._getRawStylesheet());
+ assertNotNull(st.getCTStylesheet());
assertEquals(2, st._getXfsSize());
assertEquals(1, st._getStyleXfsSize());
assertEquals(2, st._getNumberFormatSize());
--- /dev/null
+/* ====================================================================\r
+ Licensed to the Apache Software Foundation (ASF) under one or more\r
+ contributor license agreements. See the NOTICE file distributed with\r
+ this work for additional information regarding copyright ownership.\r
+ The ASF licenses this file to You under the Apache License, Version 2.0\r
+ (the "License"); you may not use this file except in compliance with\r
+ the License. You may obtain a copy of the License at\r
+\r
+ http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+ Unless required by applicable law or agreed to in writing, software\r
+ distributed under the License is distributed on an "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ See the License for the specific language governing permissions and\r
+ limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.xssf.usermodel;\r
+\r
+import junit.framework.TestCase;\r
+import org.apache.poi.xssf.XSSFTestDataSamples;\r
+\r
+/**\r
+ * @author Yegor Kozlov\r
+ */\r
+public class TestSheetHiding extends TestCase {\r
+ private XSSFWorkbook wbH;\r
+ private XSSFWorkbook wbU;\r
+\r
+ protected void setUp() {\r
+ wbH = XSSFTestDataSamples.openSampleWorkbook("TwoSheetsOneHidden.xlsx");\r
+ wbU = XSSFTestDataSamples.openSampleWorkbook("TwoSheetsNoneHidden.xlsx");\r
+ }\r
+\r
+ /**\r
+ * Test that we get the right number of sheets,\r
+ * with the right text on them, no matter what\r
+ * the hidden flags are\r
+ */\r
+ public void testTextSheets() throws Exception {\r
+ // Both should have two sheets\r
+ assertEquals(2, wbH.getNumberOfSheets());\r
+ assertEquals(2, wbU.getNumberOfSheets());\r
+\r
+ // All sheets should have one row\r
+ assertEquals(0, wbH.getSheetAt(0).getLastRowNum());\r
+ assertEquals(0, wbH.getSheetAt(1).getLastRowNum());\r
+ assertEquals(0, wbU.getSheetAt(0).getLastRowNum());\r
+ assertEquals(0, wbU.getSheetAt(1).getLastRowNum());\r
+\r
+ // All rows should have one column\r
+ assertEquals(1, wbH.getSheetAt(0).getRow(0).getLastCellNum());\r
+ assertEquals(1, wbH.getSheetAt(1).getRow(0).getLastCellNum());\r
+ assertEquals(1, wbU.getSheetAt(0).getRow(0).getLastCellNum());\r
+ assertEquals(1, wbU.getSheetAt(1).getRow(0).getLastCellNum());\r
+\r
+ // Text should be sheet based\r
+ assertEquals("Sheet1A1", wbH.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().getString());\r
+ assertEquals("Sheet2A1", wbH.getSheetAt(1).getRow(0).getCell(0).getRichStringCellValue().getString());\r
+ assertEquals("Sheet1A1", wbU.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().getString());\r
+ assertEquals("Sheet2A1", wbU.getSheetAt(1).getRow(0).getCell(0).getRichStringCellValue().getString());\r
+ }\r
+\r
+ /**\r
+ * Check that we can get and set the hidden flags\r
+ * as expected\r
+ */\r
+ public void testHideUnHideFlags() throws Exception {\r
+ assertTrue(wbH.isSheetHidden(0));\r
+ assertFalse(wbH.isSheetHidden(1));\r
+ assertFalse(wbU.isSheetHidden(0));\r
+ assertFalse(wbU.isSheetHidden(1));\r
+ }\r
+\r
+ /**\r
+ * Turn the sheet with none hidden into the one with\r
+ * one hidden\r
+ */\r
+ public void testHide() throws Exception {\r
+ wbU.setSheetHidden(0, true);\r
+ assertTrue(wbU.isSheetHidden(0));\r
+ assertFalse(wbU.isSheetHidden(1));\r
+ XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wbU);\r
+ assertTrue(wb2.isSheetHidden(0));\r
+ assertFalse(wb2.isSheetHidden(1));\r
+ }\r
+\r
+ /**\r
+ * Turn the sheet with one hidden into the one with\r
+ * none hidden\r
+ */\r
+ public void testUnHide() throws Exception {\r
+ wbH.setSheetHidden(0, false);\r
+ assertFalse(wbH.isSheetHidden(0));\r
+ assertFalse(wbH.isSheetHidden(1));\r
+ XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wbH);\r
+ assertFalse(wb2.isSheetHidden(0));\r
+ assertFalse(wb2.isSheetHidden(1));\r
+ }\r
+}\r
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
-import org.apache.poi.xssf.usermodel.extensions.XSSFColor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
protected void setUp() {
stylesTable = new StylesTable();
- ctStylesheet = stylesTable._getRawStylesheet();
+ ctStylesheet = stylesTable.getCTStylesheet();
ctBorderA = CTBorder.Factory.newInstance();
XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA);
public void testGetSetBottomBorderColor() {
//defaults
assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getBottomBorderColor());
- assertNull(cellStyle.getBottomBorderRgbColor());
+ assertNull(cellStyle.getBottomBorderXSSFColor());
int num = stylesTable.getBorders().size();
//setting indexed color
cellStyle.setBottomBorderColor(IndexedColors.BLUE_GREY.getIndex());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getBottomBorderColor());
- clr = cellStyle.getBottomBorderRgbColor();
+ clr = cellStyle.getBottomBorderXSSFColor();
assertTrue(clr.getCTColor().isSetIndexed());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed());
//a new border was added to the styles table
num = stylesTable.getBorders().size();
clr = new XSSFColor(java.awt.Color.CYAN);
cellStyle.setBottomBorderColor(clr);
- assertEquals(clr.getCTColor().toString(), cellStyle.getBottomBorderRgbColor().getCTColor().toString());
- byte[] rgb = cellStyle.getBottomBorderRgbColor().getRgb();
+ assertEquals(clr.getCTColor().toString(), cellStyle.getBottomBorderXSSFColor().getCTColor().toString());
+ byte[] rgb = cellStyle.getBottomBorderXSSFColor().getRgb();
assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
//another border was added to the styles table
assertEquals(num + 1, stylesTable.getBorders().size());
//passing null unsets the color
cellStyle.setBottomBorderColor(null);
- assertNull(cellStyle.getBottomBorderRgbColor());
+ assertNull(cellStyle.getBottomBorderXSSFColor());
}
public void testGetSetTopBorderColor() {
//defaults
assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getTopBorderColor());
- assertNull(cellStyle.getTopBorderRgbColor());
+ assertNull(cellStyle.getTopBorderXSSFColor());
int num = stylesTable.getBorders().size();
//setting indexed color
cellStyle.setTopBorderColor(IndexedColors.BLUE_GREY.getIndex());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getTopBorderColor());
- clr = cellStyle.getTopBorderRgbColor();
+ clr = cellStyle.getTopBorderXSSFColor();
assertTrue(clr.getCTColor().isSetIndexed());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed());
//a new border was added to the styles table
num = stylesTable.getBorders().size();
clr = new XSSFColor(java.awt.Color.CYAN);
cellStyle.setTopBorderColor(clr);
- assertEquals(clr.getCTColor().toString(), cellStyle.getTopBorderRgbColor().getCTColor().toString());
- byte[] rgb = cellStyle.getTopBorderRgbColor().getRgb();
+ assertEquals(clr.getCTColor().toString(), cellStyle.getTopBorderXSSFColor().getCTColor().toString());
+ byte[] rgb = cellStyle.getTopBorderXSSFColor().getRgb();
assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
//another border was added to the styles table
assertEquals(num + 1, stylesTable.getBorders().size());
//passing null unsets the color
cellStyle.setTopBorderColor(null);
- assertNull(cellStyle.getTopBorderRgbColor());
+ assertNull(cellStyle.getTopBorderXSSFColor());
}
public void testGetSetLeftBorderColor() {
//defaults
assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getLeftBorderColor());
- assertNull(cellStyle.getLeftBorderRgbColor());
+ assertNull(cellStyle.getLeftBorderXSSFColor());
int num = stylesTable.getBorders().size();
//setting indexed color
cellStyle.setLeftBorderColor(IndexedColors.BLUE_GREY.getIndex());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getLeftBorderColor());
- clr = cellStyle.getLeftBorderRgbColor();
+ clr = cellStyle.getLeftBorderXSSFColor();
assertTrue(clr.getCTColor().isSetIndexed());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed());
//a new border was added to the styles table
num = stylesTable.getBorders().size();
clr = new XSSFColor(java.awt.Color.CYAN);
cellStyle.setLeftBorderColor(clr);
- assertEquals(clr.getCTColor().toString(), cellStyle.getLeftBorderRgbColor().getCTColor().toString());
- byte[] rgb = cellStyle.getLeftBorderRgbColor().getRgb();
+ assertEquals(clr.getCTColor().toString(), cellStyle.getLeftBorderXSSFColor().getCTColor().toString());
+ byte[] rgb = cellStyle.getLeftBorderXSSFColor().getRgb();
assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
//another border was added to the styles table
assertEquals(num + 1, stylesTable.getBorders().size());
//passing null unsets the color
cellStyle.setLeftBorderColor(null);
- assertNull(cellStyle.getLeftBorderRgbColor());
+ assertNull(cellStyle.getLeftBorderXSSFColor());
}
public void testGetSetRightBorderColor() {
//defaults
assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getRightBorderColor());
- assertNull(cellStyle.getRightBorderRgbColor());
+ assertNull(cellStyle.getRightBorderXSSFColor());
int num = stylesTable.getBorders().size();
//setting indexed color
cellStyle.setRightBorderColor(IndexedColors.BLUE_GREY.getIndex());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getRightBorderColor());
- clr = cellStyle.getRightBorderRgbColor();
+ clr = cellStyle.getRightBorderXSSFColor();
assertTrue(clr.getCTColor().isSetIndexed());
assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed());
//a new border was added to the styles table
num = stylesTable.getBorders().size();
clr = new XSSFColor(java.awt.Color.CYAN);
cellStyle.setRightBorderColor(clr);
- assertEquals(clr.getCTColor().toString(), cellStyle.getRightBorderRgbColor().getCTColor().toString());
- byte[] rgb = cellStyle.getRightBorderRgbColor().getRgb();
+ assertEquals(clr.getCTColor().toString(), cellStyle.getRightBorderXSSFColor().getCTColor().toString());
+ byte[] rgb = cellStyle.getRightBorderXSSFColor().getRgb();
assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
//another border was added to the styles table
assertEquals(num + 1, stylesTable.getBorders().size());
//passing null unsets the color
cellStyle.setRightBorderColor(null);
- assertNull(cellStyle.getRightBorderRgbColor());
+ assertNull(cellStyle.getRightBorderXSSFColor());
}
public void testGetSetFillBackgroundColor() {
assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor());
- assertNull(cellStyle.getFillBackgroundRgbColor());
+ assertNull(cellStyle.getFillBackgroundXSSFColor());
XSSFColor clr;
//setting indexed color
cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex());
assertEquals(IndexedColors.RED.getIndex(), cellStyle.getFillBackgroundColor());
- clr = cellStyle.getFillBackgroundRgbColor();
+ clr = cellStyle.getFillBackgroundXSSFColor();
assertTrue(clr.getCTColor().isSetIndexed());
assertEquals(IndexedColors.RED.getIndex(), clr.getIndexed());
//a new fill was added to the styles table
num = stylesTable.getFills().size();
clr = new XSSFColor(java.awt.Color.CYAN);
cellStyle.setFillBackgroundColor(clr);
- assertEquals(clr.getCTColor().toString(), cellStyle.getFillBackgroundRgbColor().getCTColor().toString());
- byte[] rgb = cellStyle.getFillBackgroundRgbColor().getRgb();
+ assertEquals(clr.getCTColor().toString(), cellStyle.getFillBackgroundXSSFColor().getCTColor().toString());
+ byte[] rgb = cellStyle.getFillBackgroundXSSFColor().getRgb();
assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
//another border was added to the styles table
assertEquals(num + 1, stylesTable.getFills().size());
//passing null unsets the color
cellStyle.setFillBackgroundColor(null);
- assertNull(cellStyle.getFillBackgroundRgbColor());
+ assertNull(cellStyle.getFillBackgroundXSSFColor());
assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor());
}
XSSFCellStyle style1 = wb1.createCellStyle();
assertEquals(IndexedColors.AUTOMATIC.getIndex(), style1.getFillBackgroundColor());
- assertNull(style1.getFillBackgroundRgbColor());
+ assertNull(style1.getFillBackgroundXSSFColor());
//compatibility with HSSF
HSSFWorkbook wb2 = new HSSFWorkbook();
XSSFCellStyle defaultStyle = wb.getCellStyleAt((short)0);
assertEquals(IndexedColors.AUTOMATIC.getIndex(), defaultStyle.getFillForegroundColor());
- assertEquals(null, defaultStyle.getFillForegroundRgbColor());
+ assertEquals(null, defaultStyle.getFillForegroundXSSFColor());
assertEquals(CellStyle.NO_FILL, defaultStyle.getFillPattern());
XSSFCellStyle customStyle = wb.createCellStyle();
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.XSSFTestDataSamples;
-import org.apache.poi.xssf.usermodel.extensions.XSSFColor;
+import org.apache.poi.xssf.usermodel.XSSFColor;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBooleanProperty;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont;
ctFont.setColorArray(0,color);
XSSFFont xssfFont=new XSSFFont(ctFont);
- assertEquals(ctFont.getColorArray(0).getRgb()[0],xssfFont.getRgbColor().getRgb()[0]);
- assertEquals(ctFont.getColorArray(0).getRgb()[1],xssfFont.getRgbColor().getRgb()[1]);
- assertEquals(ctFont.getColorArray(0).getRgb()[2],xssfFont.getRgbColor().getRgb()[2]);
- assertEquals(ctFont.getColorArray(0).getRgb()[3],xssfFont.getRgbColor().getRgb()[3]);
+ assertEquals(ctFont.getColorArray(0).getRgb()[0],xssfFont.getXSSFColor().getRgb()[0]);
+ assertEquals(ctFont.getColorArray(0).getRgb()[1],xssfFont.getXSSFColor().getRgb()[1]);
+ assertEquals(ctFont.getColorArray(0).getRgb()[2],xssfFont.getXSSFColor().getRgb()[2]);
+ assertEquals(ctFont.getColorArray(0).getRgb()[3],xssfFont.getXSSFColor().getRgb()[3]);
color.setRgb(Integer.toHexString(0xF1F1F1).getBytes());
XSSFColor newColor=new XSSFColor(color);
- xssfFont.setRgbColor(newColor);
+ xssfFont.setColor(newColor);
assertEquals(ctFont.getColorArray(0).getRgb()[2],newColor.getRgb()[2]);
}
assertEquals("'Testing Named Ranges'!$A$1:$B$1", name1.getReference());\r
assertEquals("Testing Named Ranges", name1.getSheetName());\r
\r
- //setting invalid reference should throw IllegalArgumentException\r
- try {\r
- name1.setReference("invalid");\r
- fail("expected exception");\r
- } catch (IllegalArgumentException e){\r
- ;\r
- }\r
-\r
assertEquals(-1, name1.getLocalSheetId());\r
name1.setLocalSheetId(1);\r
assertEquals(1, name1.getLocalSheetId());\r
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.util.Region;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.model.CommentsTable;
import org.apache.poi.xssf.model.StylesTable;
XSSFComment comment = sheet.createComment();
Cell cell = sheet.createRow(0).createCell((short)0);
- CommentsTable comments = (CommentsTable)sheet.getCommentsSourceIfExists();
+ CommentsTable comments = sheet.getCommentsTable();
CTComments ctComments = comments.getCTComments();
sheet.setCellComment("A1", comment);
sheet.setDefaultColumnStyle((short) 3, cellStyle);
assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle());
- XSSFRow row = sheet.createRow(0);
- XSSFCell cell = sheet.getRow(0).createCell(3);
-
}
assertEquals(7,cols.sizeOfColArray());
colArray=cols.getColArray();
assertEquals(3, colArray[1].getOutlineLevel());
- assertEquals(3,sheet.getSheetTypeSheetFormatPr().getOutlineLevelCol());
+ assertEquals(3,sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol());
sheet.ungroupColumn((short)8,(short) 10);
colArray=cols.getColArray();
sheet.ungroupColumn((short)2,(short)2);
colArray=cols.getColArray();
assertEquals(4, colArray.length);
- assertEquals(2,sheet.getSheetTypeSheetFormatPr().getOutlineLevelCol());
+ assertEquals(2,sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol());
}
assertNotNull(ctrow);
assertEquals(9,ctrow.getR());
assertEquals(1, ctrow.getOutlineLevel());
- assertEquals(1,sheet.getSheetTypeSheetFormatPr().getOutlineLevelRow());
+ assertEquals(1,sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow());
//two level
sheet.groupRow(10,13);
assertNotNull(ctrow);
assertEquals(10,ctrow.getR());
assertEquals(2, ctrow.getOutlineLevel());
- assertEquals(2,sheet.getSheetTypeSheetFormatPr().getOutlineLevelRow());
+ assertEquals(2,sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow());
sheet.ungroupRow(8, 10);
assertEquals(4,sheet.getPhysicalNumberOfRows());
- assertEquals(1,sheet.getSheetTypeSheetFormatPr().getOutlineLevelRow());
+ assertEquals(1,sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow());
sheet.ungroupRow(10,10);
assertEquals(3,sheet.getPhysicalNumberOfRows());
- assertEquals(1,sheet.getSheetTypeSheetFormatPr().getOutlineLevelRow());
+ assertEquals(1,sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow());
}
- public void testSetZoom() {
- Workbook workBook = new XSSFWorkbook();
- XSSFSheet sheet1 = (XSSFSheet) workBook.createSheet("new sheet");
- sheet1.setZoom(3,4); // 75 percent magnification
- long zoom = sheet1.getSheetTypeSheetView().getZoomScale();
- assertEquals(zoom, 75);
- }
+ public void testSetZoom() {
+ XSSFWorkbook workBook = new XSSFWorkbook();
+ XSSFSheet sheet1 = workBook.createSheet("new sheet");
+ sheet1.setZoom(3,4); // 75 percent magnification
+ long zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale();
+ assertEquals(zoom, 75);
+
+ sheet1.setZoom(200);
+ zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale();
+ assertEquals(zoom, 200);
+
+ try {
+ sheet1.setZoom(500);
+ fail("Expecting exception");
+ } catch (IllegalArgumentException e){
+ assertEquals("Valid scale values range from 10 to 400", e.getMessage());
+ }
+ }
public void testOutlineProperties() {
XSSFWorkbook wb = new XSSFWorkbook();
//get custom style
StylesTable styleSource = workbook.getStylesSource();
- CellStyle customStyle = new XSSFCellStyle(styleSource);
- Font font = new XSSFFont();
+ XSSFCellStyle customStyle = new XSSFCellStyle(styleSource);
+ XSSFFont font = new XSSFFont();
font.setFontName("Verdana");
customStyle.setFont(font);
int x = styleSource.putStyle(customStyle);
assertNotNull(fontAt);
//get customized font
- Font customFont = new XSSFFont();
+ XSSFFont customFont = new XSSFFont();
customFont.setItalic(true);
int x = styleSource.putFont(customFont);
fontAt = workbook.getFontAt((short)x);
// Has 8 number formats
assertEquals(8, st._getNumberFormatSize());
// Has 2 fonts
- assertEquals(2, st._getFontsSize());
+ assertEquals(2, st.getFonts().size());
// Has 2 fills
- assertEquals(2, st._getFillsSize());
+ assertEquals(2, st.getFills().size());
// Has 1 border
- assertEquals(1, st._getBordersSize());
+ assertEquals(1, st.getBorders().size());
// Add two more styles
assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8,
assertNotNull(ss);
assertEquals(10, st._getNumberFormatSize());
- assertEquals(2, st._getFontsSize());
- assertEquals(2, st._getFillsSize());
- assertEquals(1, st._getBordersSize());
+ assertEquals(2, st.getFonts().size());
+ assertEquals(2, st.getFills().size());
+ assertEquals(1, st.getBorders().size());
}
public void testNamedRanges() {