Browse Source

1. implemented XSSFSheet.autosizeColumn(), for now mostly duplicated HSSF code, will be refactored in future.2. fixed bug #45974: XSSFCell.getCellStyle can return null3. more code cleanup and reaftoring, removed usages of obsolete XSSFCell.getCellNum() in favor of XSSFCell.getColumnIndex(), also more javadoc in core classes

4. fixed a blocker: calling XSSFSheet.getNumMergedRegions() resulted in unreadable workbook, this methods structurally modified worksheet and added unnecessary data 

git-svn-id: https://svn.apache.org/repos/asf/poi/branches/ooxml@706691 13f79535-47bb-0310-9956-ffa450edef68
pull/6/head
Yegor Kozlov 15 years ago
parent
commit
b15942d4a8
25 changed files with 449 additions and 297 deletions
  1. 1
    1
      src/examples/jsp/HSSFExample.jsp
  2. 1
    1
      src/examples/src/org/apache/poi/ss/usermodel/examples/FromQuickGuide.java
  3. 1
    1
      src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java
  4. 4
    10
      src/ooxml/interfaces-jdk15/org/apache/poi/ss/usermodel/Row.java
  5. 9
    26
      src/ooxml/interfaces-jdk15/org/apache/poi/ss/usermodel/Sheet.java
  6. 2
    30
      src/ooxml/interfaces-jdk15/org/apache/poi/ss/usermodel/Workbook.java
  7. 9
    0
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAnchor.java
  8. 12
    9
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java
  9. 18
    5
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java
  10. 4
    0
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDialogsheet.java
  11. 1
    1
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java
  12. 1
    3
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFont.java
  13. 55
    51
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFName.java
  14. 1
    7
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java
  15. 1
    0
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java
  16. 65
    9
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRow.java
  17. 44
    51
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java
  18. 11
    36
      src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
  19. 174
    0
      src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java
  20. 4
    11
      src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java
  21. 4
    4
      src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java
  22. 1
    3
      src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java
  23. 6
    6
      src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java
  24. 19
    29
      src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java
  25. 1
    3
      src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java

+ 1
- 1
src/examples/jsp/HSSFExample.jsp View File

%> %>
<%= "CELL col=" <%= "CELL col="
+ cell.getCellNum()
+ cell.getColumnIndex()
+ " VALUE=" + value %> + " VALUE=" + value %>
<% <%
} }

+ 1
- 1
src/examples/src/org/apache/poi/ss/usermodel/examples/FromQuickGuide.java View File

public static void getCellContents(Sheet sheet) { public static void getCellContents(Sheet sheet) {
for (Row row : sheet) { for (Row row : sheet) {
for (Cell cell : row) { for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum());
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString()); System.out.print(cellRef.formatAsString());
System.out.print(" - "); System.out.print(" - ");

+ 1
- 1
src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java View File

public class IterateCells { public class IterateCells {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook(args[0]);
Workbook wb = null;
for (int i = 0; i < wb.getNumberOfSheets(); i++) { for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i); Sheet sheet = wb.getSheetAt(i);
System.out.println(wb.getSheetName(i)); System.out.println(wb.getSheetName(i));

+ 4
- 10
src/ooxml/interfaces-jdk15/org/apache/poi/ss/usermodel/Row.java View File

* *
* @param column - the column number this cell represents * @param column - the column number this cell represents
* *
* @return HSSFCell a high level representation of the created cell.
* @return Cell a high level representation of the created cell.
*/ */
Cell createCell(int column, int type); Cell createCell(int column, int type);


/** /**
* remove the HSSFCell from this row.
* remove the Cell from this row.
* @param cell to remove * @param cell to remove
*/ */
void removeCell(Cell cell); void removeCell(Cell cell);
int getRowNum(); int getRowNum();


/** /**
* get the hssfcell representing a given column (logical cell) 0-based. If you
* get the cell representing a given column (logical cell) 0-based. If you
* ask for a cell that is not defined....you get a null. * ask for a cell that is not defined....you get a null.
* *
* @param cellnum 0 based column number * @param cellnum 0 based column number
Cell getCell(int cellnum); Cell getCell(int cellnum);
/** /**
* Get the hssfcell representing a given column (logical cell)
* Get the cell representing a given column (logical cell)
* 0-based. If you ask for a cell that is not defined, then * 0-based. If you ask for a cell that is not defined, then
* your supplied policy says what to do * your supplied policy says what to do
* *
*/ */
Iterator<Cell> cellIterator(); Iterator<Cell> cellIterator();


/**
* Alias for {@link #cellIterator()} to allow
* foreach loops
*/
Iterator<Cell> iterator();

/** /**
* Used to specify the different possible policies * Used to specify the different possible policies
* if for the case of null and blank cells * if for the case of null and blank cells

+ 9
- 26
src/ooxml/interfaces-jdk15/org/apache/poi/ss/usermodel/Sheet.java View File



import java.util.Iterator; import java.util.Iterator;


import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.util.PaneInformation; import org.apache.poi.hssf.util.PaneInformation;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.Region; import org.apache.poi.ss.util.Region;
public interface Sheet extends Iterable<Row> { public interface Sheet extends Iterable<Row> {


/* Constants for margins */ /* Constants for margins */
public static final short LeftMargin = Sheet.LeftMargin;
public static final short LeftMargin = 0;


public static final short RightMargin = Sheet.RightMargin;
public static final short RightMargin = 1;


public static final short TopMargin = Sheet.TopMargin;
public static final short TopMargin = 2;


public static final short BottomMargin = Sheet.BottomMargin;
public static final short BottomMargin = 3;

public static final short HeaderMargin = 4;

public static final short FooterMargin = 5;


public static final byte PANE_LOWER_RIGHT = (byte) 0; public static final byte PANE_LOWER_RIGHT = (byte) 0;


* @param rownum row number * @param rownum row number
* @return High level HSSFRow object representing a row in the sheet * @return High level HSSFRow object representing a row in the sheet
* @see org.apache.poi.hssf.usermodel.HSSFRow * @see org.apache.poi.hssf.usermodel.HSSFRow
* @see #removeRow(HSSFRow)
* @see #removeRow(Row)
*/ */
Row createRow(int rownum); Row createRow(int rownum);


* be the third row if say for instance the second row is undefined. * be the third row if say for instance the second row is undefined.
*/ */
Iterator<Row> rowIterator(); Iterator<Row> rowIterator();
/**
* Alias for {@link #rowIterator()} to allow
* foreach loops
*/
Iterator<Row> iterator();


/** /**
* whether alternate expression evaluation is on * whether alternate expression evaluation is on


void setAutobreaks(boolean b); void setAutobreaks(boolean b);


/**
* set whether sheet is a dialog sheet or not
* @param b isDialog or not
*/

void setDialog(boolean b);

/** /**
* set whether to display the guts or not * set whether to display the guts or not
* *


boolean getAutobreaks(); boolean getAutobreaks();


/**
* get whether sheet is a dialog sheet or not
* @return isDialog or not
*/

boolean getDialog();

/** /**
* get whether to display the guts or not * get whether to display the guts or not
* *

+ 2
- 30
src/ooxml/interfaces-jdk15/org/apache/poi/ss/usermodel/Workbook.java View File



void removeSheetAt(int index); void removeSheetAt(int index);
/**
* determine whether the Excel GUI will backup the workbook when saving.
*
* @param backupValue true to indicate a backup will be performed.
*/

void setBackupFlag(boolean backupValue);

/**
* determine whether the Excel GUI will backup the workbook when saving.
*
* @return the current setting for backups.
*/

boolean getBackupFlag();

/** /**
* Sets the repeating rows and columns for a sheet (as found in * Sets the repeating rows and columns for a sheet (as found in
* File->PageSetup->Sheet). This is function is included in the workbook * File->PageSetup->Sheet). This is function is included in the workbook
* Sets the policy on what to do when * Sets the policy on what to do when
* getting missing or blank cells from a row. * getting missing or blank cells from a row.
* This will then apply to all calls to * This will then apply to all calls to
* {@link Row.getCell()}. See
* {@link Row#getCell(int)} }. See
* {@link MissingCellPolicy} * {@link MissingCellPolicy}
*/ */
void setMissingCellPolicy(MissingCellPolicy missingCellPolicy); void setMissingCellPolicy(MissingCellPolicy missingCellPolicy);
*/ */
List getAllPictures(); List getAllPictures();


/**
* protect a workbook with a password (not encypted, just sets writeprotect
* flags and the password.
* @param password to set
*/
void writeProtectWorkbook(String password, String username);

/**
* removes the write protect flag
*/
void unwriteProtectWorkbook();

/** /**
* Gets all embedded OLE2 objects from the Workbook. * Gets all embedded OLE2 objects from the Workbook.
* *
* @return the list of embedded objects (a list of {@link HSSFObjectData} objects.)
* @return the list of embedded objects
*/ */
List getAllEmbeddedObjects(); List getAllEmbeddedObjects();



+ 9
- 0
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAnchor.java View File

* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public abstract class XSSFAnchor { public abstract class XSSFAnchor {
public abstract int getDx1();
public abstract void setDx1( int dx1 );
public abstract int getDy1();
public abstract void setDy1( int dy1 );
public abstract int getDy2();
public abstract void setDy2( int dy2 );
public abstract int getDx2();
public abstract void setDx2( int dx2 );
} }

+ 12
- 9
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java View File

} }


public Comment getCellComment() { public Comment getCellComment() {
return row.getSheet().getCellComment(row.getRowNum(), getCellNum());
return row.getSheet().getCellComment(row.getRowNum(), getColumnIndex());
} }


public String getCellFormula() { public String getCellFormula() {
return row.getRowNum(); return row.getRowNum();
} }


/**
* Return the cell's style.
*
* @return the cell's style. Always not-null. Default cell style has zero index and can be obtained as
* <code>workbook.getCellStyleAt(0)</code>
*/
public XSSFCellStyle getCellStyle() { public XSSFCellStyle getCellStyle() {
// Zero is the empty default
if(this.cell.getS() > 0) {
return stylesSource.getStyleAt(this.cell.getS());
}
return null;
long idx = cell.isSetS() ? cell.getS() : 0;
return stylesSource.getStyleAt(idx);
} }


public int getCellType() { public int getCellType() {
public Date getDateCellValue() { public Date getDateCellValue() {
if (STCellType.N == this.cell.getT() || STCellType.STR == this.cell.getT()) { if (STCellType.N == this.cell.getT() || STCellType.STR == this.cell.getT()) {
double value = this.getNumericCellValue(); double value = this.getNumericCellValue();
if (false /* book.isUsing1904DateWindowing() */) { // FIXME
if (row.getSheet().getWorkbook().isDate1904()) {
return DateUtil.getJavaDate(value,true); return DateUtil.getJavaDate(value,true);
} }
else { else {


public void setCellComment(Comment comment) { public void setCellComment(Comment comment) {
String cellRef = new CellReference(row.getRowNum(), getCellNum()).formatAsString();
String cellRef = new CellReference(row.getRowNum(), getColumnIndex()).formatAsString();
row.getSheet().setCellComment(cellRef, (XSSFComment)comment); row.getSheet().setCellComment(cellRef, (XSSFComment)comment);
} }


} }


protected String formatPosition() { protected String formatPosition() {
int col = this.getCellNum();
int col = this.getColumnIndex();
String result = Character.valueOf((char) (col % 26 + 'A')).toString(); String result = Character.valueOf((char) (col % 26 + 'A')).toString();
if (col >= 26){ if (col >= 26){
col = col / 26; col = col / 26;

+ 18
- 5
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java View File

* @return HorizontalAlignment - the type of alignment * @return HorizontalAlignment - the type of alignment
*/ */
public HorizontalAlignment getAlignmentEnum() { public HorizontalAlignment getAlignmentEnum() {
return getCellAlignment().getHorizontal();
CTCellAlignment align = cellXf.getAlignment();
if(align != null && align.isSetHorizontal()) {
return HorizontalAlignment.values()[align.getHorizontal().intValue()-1];
} else {
return HorizontalAlignment.GENERAL;
}
} }


/** /**
* @return indent - number of spaces * @return indent - number of spaces
*/ */
public short getIndention() { public short getIndention() {
return (short) getCellAlignment().getIndent();
CTCellAlignment align = cellXf.getAlignment();
return (short)(align == null ? 0 : align.getIndent());
} }


/** /**
* @return rotation degrees (between 0 and 180 degrees) * @return rotation degrees (between 0 and 180 degrees)
*/ */
public short getRotation() { public short getRotation() {
return (short) getCellAlignment().getTextRotation();
CTCellAlignment align = cellXf.getAlignment();
return (short)(align == null ? 0 : align.getTextRotation());
} }


/** /**
* @see VerticalAlignment * @see VerticalAlignment
*/ */
public VerticalAlignment getVerticalAlignmentEnum() { public VerticalAlignment getVerticalAlignmentEnum() {
return getCellAlignment().getVertical();
CTCellAlignment align = cellXf.getAlignment();
if(align != null && align.isSetVertical()) {
return VerticalAlignment.values()[align.getVertical().intValue()-1];
} else {
return VerticalAlignment.BOTTOM;
}
} }


/** /**
* @return a boolean value indicating if the text in a cell should be line-wrapped within the cell. * @return a boolean value indicating if the text in a cell should be line-wrapped within the cell.
*/ */
public boolean getWrapText() { public boolean getWrapText() {
return getCellAlignment().getWrapText();
CTCellAlignment align = cellXf.getAlignment();
return align != null && align.getWrapText();
} }


/** /**

+ 4
- 0
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDialogsheet.java View File

import java.io.IOException; import java.io.IOException;


public class XSSFDialogsheet extends XSSFSheet implements Sheet{ public class XSSFDialogsheet extends XSSFSheet implements Sheet{
protected CTDialogsheet dialogsheet;


public XSSFDialogsheet(XSSFSheet sheet) { public XSSFDialogsheet(XSSFSheet sheet) {
this.packagePart = sheet.getPackagePart(); this.packagePart = sheet.getPackagePart();
return dialogsheet.getSheetProtection(); return dialogsheet.getSheetProtection();
} }


public boolean getDialog(){
return true;
}
} }

+ 1
- 1
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java View File

return _cell.getCellType(); return _cell.getCellType();
} }
public int getColumnIndex() { public int getColumnIndex() {
return _cell.getCellNum();
return _cell.getColumnIndex();
} }
public int getErrorCellValue() { public int getErrorCellValue() {
return _cell.getErrorCellValue(); return _cell.getErrorCellValue();

+ 1
- 3
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFont.java View File





public String toString() { public String toString() {
return "org.apache.poi.xssf.usermodel.XSSFFont{" +
ctFont +
"}";
return ctFont.toString();
} }





+ 55
- 51
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFName.java View File

/** /**
* this defined name specifies the workbook's print area * this defined name specifies the workbook's print area
*/ */
public final static String BUILTIN_PRINT_AREA = "_xlnm.Print_Area";
public final static String BUILTIN_PRINT_AREA = "_xlnm.Print_Area";


/** /**
* this defined name specifies the row(s) or column(s) to repeat * this defined name specifies the row(s) or column(s) to repeat
* at the top of each printed page.
* at the top of each printed page.
*/ */
public final static String BUILTIN_PRINT_TITLE = "_xlnm.Print_Titles";
public final static String BUILTIN_PRINT_TITLE = "_xlnm.Print_Titles";


//Filter & Advanced Filter //Filter & Advanced Filter


* this defined name refers to a range containing the criteria values * this defined name refers to a range containing the criteria values
* to be used in applying an advanced filter to a range of data * to be used in applying an advanced filter to a range of data
*/ */
public final static String BUILTIN_CRITERIA = "_xlnm.Criteria:";
public final static String BUILTIN_CRITERIA = "_xlnm.Criteria:";




/** /**
* output values resulting from applying an advanced filter criteria to a source * output values resulting from applying an advanced filter criteria to a source
* range * range
*/ */
public final static String BUILTIN_EXTRACT = "_xlnm.Extract:";
public final static String BUILTIN_EXTRACT = "_xlnm.Extract:";


/** /**
* can be one of the following * can be one of the following
* b. This defined name refers to a range to which an AutoFilter has been * b. This defined name refers to a range to which an AutoFilter has been
* applied * applied
*/ */
public final static String BUILTIN_FILTER_DB = "_xlnm._FilterDatabase:";

public final static String BUILTIN_FILTER_DB = "_xlnm._FilterDatabase:";


//Miscellaneous //Miscellaneous


/** /**
* the defined name refers to a consolidation area * the defined name refers to a consolidation area
*/ */
public final static String BUILTIN_CONSOLIDATE_AREA = "_xlnm.Consolidate_Area";
public final static String BUILTIN_CONSOLIDATE_AREA = "_xlnm.Consolidate_Area";


/** /**
* the range specified in the defined name is from a database data source * the range specified in the defined name is from a database data source
*/ */
public final static String BUILTIN_DATABASE = "_xlnm.Database";
public final static String BUILTIN_DATABASE = "_xlnm.Database";


/** /**
* the defined name refers to a sheet title. * the defined name refers to a sheet title.
*/ */
public final static String BUILTIN_SHEET_TITLE = "_xlnm.Sheet_Title";
public final static String BUILTIN_SHEET_TITLE = "_xlnm.Sheet_Title";


private XSSFWorkbook workbook; private XSSFWorkbook workbook;
private CTDefinedName ctName; private CTDefinedName ctName;


protected XSSFName(XSSFWorkbook workbook) { protected XSSFName(XSSFWorkbook workbook) {
this.workbook = workbook;
this.ctName = CTDefinedName.Factory.newInstance();
this.workbook = workbook;
this.ctName = CTDefinedName.Factory.newInstance();
} }

protected XSSFName(CTDefinedName name, XSSFWorkbook workbook) { protected XSSFName(CTDefinedName name, XSSFWorkbook workbook) {
this.workbook = workbook;
this.ctName = name;
this.workbook = workbook;
this.ctName = name;
} }


public boolean isFunctionName() { public boolean isFunctionName() {
// TODO Figure out how HSSF does this, and do the same!
return ctName.getFunction(); // maybe this works - verify
// TODO Figure out how HSSF does this, and do the same!
return ctName.getFunction(); // maybe this works - verify
} }

/** /**
* Returns the underlying named range object * Returns the underlying named range object
*/ */
protected CTDefinedName getCTName() { protected CTDefinedName getCTName() {
return ctName;
return ctName;
} }


public String getNameName() { public String getNameName() {
return ctName.getName();
return ctName.getName();
} }

public void setNameName(String nameName) { public void setNameName(String nameName) {
ctName.setName(nameName);
ctName.setName(nameName);
} }


public String getReference() { public String getReference() {
return ctName.getStringValue();
return ctName.getStringValue();
} }

public void setReference(String ref) { public void setReference(String ref) {
ctName.setStringValue(ref);
ctName.setStringValue(ref);
} }


public void setLocalSheetId(int sheetId) { public void setLocalSheetId(int sheetId) {
ctName.setLocalSheetId(sheetId);
ctName.setLocalSheetId(sheetId);
} }


public int getLocalSheetId() { public int getLocalSheetId() {
return (int)ctName.getLocalSheetId();
return (int) ctName.getLocalSheetId();
} }




public void setFunction(boolean value) { public void setFunction(boolean value) {
ctName.setFunction(value);
ctName.setFunction(value);
} }


public boolean getFunction() { public boolean getFunction() {
return ctName.getFunction();
return ctName.getFunction();
} }


public void setFunctionGroupId(int functionGroupId) { public void setFunctionGroupId(int functionGroupId) {
ctName.setFunctionGroupId(functionGroupId);
ctName.setFunctionGroupId(functionGroupId);
} }


public int getFunctionGroupId() { public int getFunctionGroupId() {
return (int)ctName.getFunctionGroupId();
return (int) ctName.getFunctionGroupId();
} }


public String getSheetName() { public String getSheetName() {
if(ctName.isSetLocalSheetId()) {
// Given as explicit sheet id
long sheetId = ctName.getLocalSheetId();
if(sheetId >= 0) {
return workbook.getSheetName((int)sheetId);
}
} else {
// Is it embeded in the reference itself?
int excl = getReference().indexOf('!');
if(excl > -1) {
return getReference().substring(0, excl);
}
}
// Not given at all
return null;
if (ctName.isSetLocalSheetId()) {
// Given as explicit sheet id
long sheetId = ctName.getLocalSheetId();
if (sheetId >= 0) {
return workbook.getSheetName((int) sheetId);
}
} else {
// Is it embeded in the reference itself?
int excl = getReference().indexOf('!');
if (excl > -1) {
return getReference().substring(0, excl);
}
}
// Not given at all
return null;
} }


public String getComment() { public String getComment() {
return ctName.getComment();
return ctName.getComment();
} }

public void setComment(String comment) { public void setComment(String comment) {
ctName.setComment(comment);
ctName.setComment(comment);
} }




public int hashCode(){
return ctName.toString().hashCode();
public int hashCode() {
return ctName.toString().hashCode();
} }


public boolean equals(Object o){
if(!(o instanceof XSSFName)) return false;
XSSFName cf = (XSSFName)o;
return ctName.toString().equals(cf.getCTName().toString());
public boolean equals(Object o) {
if (!(o instanceof XSSFName)) return false;
XSSFName cf = (XSSFName) o;
return ctName.toString().equals(cf.getCTName().toString());
} }





+ 1
- 7
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java View File

*/ */
private static CTPicture prototype = null; private static CTPicture prototype = null;
/**
* Width of one character in pixels. Same for Calibry and Arial.
*/
private static final float CHARACTER_WIDTH = 7.0017f;
/** /**
* This object specifies a picture object and all its properties * This object specifies a picture object and all its properties
*/ */
XSSFSheet sheet = (XSSFSheet)getDrawing().getParent(); XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();
float numChars = (float)sheet.getColumnWidth(columnIndex)/256; float numChars = (float)sheet.getColumnWidth(columnIndex)/256;
return numChars*CHARACTER_WIDTH;
return numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH;
} }
private float getRowHeightInPixels(int rowIndex){ private float getRowHeightInPixels(int rowIndex){

+ 1
- 0
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java View File

if(c1.isSetTheme()) c2.setTheme(c1.getTheme()); if(c1.isSetTheme()) c2.setTheme(c1.getTheme());
if(c1.isSetTint()) c2.setTint(c1.getTint()); if(c1.isSetTint()) c2.setTint(c1.getTint());
} }
if(pr.sizeOfSzArray() > 0) ctFont.addNewSz().setVal(pr.getSzArray(0).getVal());
if(pr.sizeOfRFontArray() > 0) ctFont.addNewName().setVal(pr.getRFontArray(0).getVal()); if(pr.sizeOfRFontArray() > 0) ctFont.addNewName().setVal(pr.getRFontArray(0).getVal());
if(pr.sizeOfFamilyArray() > 0) ctFont.addNewFamily().setVal(pr.getFamilyArray(0).getVal()); if(pr.sizeOfFamilyArray() > 0) ctFont.addNewFamily().setVal(pr.getFamilyArray(0).getVal());
if(pr.sizeOfSchemeArray() > 0) ctFont.addNewScheme().setVal(pr.getSchemeArray(0).getVal()); if(pr.sizeOfSchemeArray() > 0) ctFont.addNewScheme().setVal(pr.getSchemeArray(0).getVal());

+ 65
- 9
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRow.java View File

import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;



/**
* High level representation of a row of a spreadsheet.
*/
public class XSSFRow implements Row, Comparable { public class XSSFRow implements Row, Comparable {


private CTRow row; private CTRow row;
public XSSFRow(CTRow row, XSSFSheet sheet) { public XSSFRow(CTRow row, XSSFSheet sheet) {
this.row = row; this.row = row;
this.sheet = sheet; this.sheet = sheet;
this.cells = new LinkedList<Cell>();
this.cells = new LinkedList<Cell>();
for (CTCell c : row.getCArray()) { for (CTCell c : row.getCArray()) {
this.cells.add(new XSSFCell(this, c)); this.cells.add(new XSSFCell(this, c));
} }
} }


/**
* Returns the XSSFSheet this row belongs to
*
* @return the XSSFSheet that owns this row
*/
public XSSFSheet getSheet() { public XSSFSheet getSheet() {
return this.sheet; return this.sheet;
} }
/**
* @return Cell iterator of the physically defined cells. Note element 4 may
* actually be row cell depending on how many are defined!
*/
public Iterator<Cell> cellIterator() { public Iterator<Cell> cellIterator() {
return cells.iterator(); return cells.iterator();
} }

/** /**
* Alias for {@link #cellIterator()} to allow * Alias for {@link #cellIterator()} to allow
* foreach loops * foreach loops
* *
* @param column Cell column number. * @param column Cell column number.
* @param index Position where to insert cell. * @param index Position where to insert cell.
* @param type TODO
* @param type cell type, one of Cell.CELL_TYPE_*
* @return The new cell. * @return The new cell.
*/ */
protected XSSFCell addCell(int column, int index, int type) { protected XSSFCell addCell(int column, int index, int type) {
Iterator<Cell> it = cellIterator(); Iterator<Cell> it = cellIterator();
for ( ; it.hasNext() ; ) { for ( ; it.hasNext() ; ) {
Cell cell = it.next(); Cell cell = it.next();
if (cell.getCellNum() == cellnum) {
if (cell.getColumnIndex() == cellnum) {
return (XSSFCell)cell; return (XSSFCell)cell;
} }
} }
/** /**
* Returns the cell at the given (0 based) index, * Returns the cell at the given (0 based) index,
* with the {@link MissingCellPolicy} from the
* parent Workbook.
* with the {@link MissingCellPolicy} from the parent Workbook.
*
* @return the cell at the given (0 based) index
*/ */
public XSSFCell getCell(int cellnum) { public XSSFCell getCell(int cellnum) {
return getCell(cellnum, sheet.getWorkbook().getMissingCellPolicy()); return getCell(cellnum, sheet.getWorkbook().getMissingCellPolicy());
/** /**
* Returns the cell at the given (0 based) index, * Returns the cell at the given (0 based) index,
* with the specified {@link MissingCellPolicy} * with the specified {@link MissingCellPolicy}
*
* @return the cell at the given (0 based) index
*/ */
public XSSFCell getCell(int cellnum, MissingCellPolicy policy) { public XSSFCell getCell(int cellnum, MissingCellPolicy policy) {
XSSFCell cell = retrieveCell(cellnum); XSSFCell cell = retrieveCell(cellnum);
throw new IllegalArgumentException("Illegal policy " + policy + " (" + policy.id + ")"); throw new IllegalArgumentException("Illegal policy " + policy + " (" + policy.id + ")");
} }


/**
* Get the number of the first cell contained in this row.
*
* @return short representing the first logical cell in the row, or -1 if the row does not contain any cells.
*/
public short getFirstCellNum() { public short getFirstCellNum() {
for (Iterator<Cell> it = cellIterator() ; it.hasNext() ; ) { for (Iterator<Cell> it = cellIterator() ; it.hasNext() ; ) {
Cell cell = it.next(); Cell cell = it.next();
if (cell != null) { if (cell != null) {
return cell.getCellNum();
return (short)cell.getColumnIndex();
} }
} }
return -1; return -1;
for (Iterator<Cell> it = cellIterator() ; it.hasNext() ; ) { for (Iterator<Cell> it = cellIterator() ; it.hasNext() ; ) {
Cell cell = it.next(); Cell cell = it.next();
if (cell != null) { if (cell != null) {
lastCellNum = (short)(cell.getCellNum() + 1);
lastCellNum = (short)(cell.getColumnIndex() + 1);
} }
} }
return lastCellNum; return lastCellNum;
} }


/**
* Gets the number of defined cells (NOT number of cells in the actual row!).
* That is to say if only columns 0,4,5 have values then there would be 3.
*
* @return int representing the number of defined cells in the row.
*/
public int getPhysicalNumberOfCells() { public int getPhysicalNumberOfCells() {
int count = 0; int count = 0;
for (Iterator<Cell> it = cellIterator() ; it.hasNext() ; ) { for (Iterator<Cell> it = cellIterator() ; it.hasNext() ; ) {
return count; return count;
} }


/**
* Get row number this row represents
*
* @return the row number (0 based)
*/
public int getRowNum() { public int getRowNum() {
return (int) (row.getR() - 1); return (int) (row.getR() - 1);
} }


/**
* Get whether or not to display this row with 0 height
*
* @return - height is zero or not.
*/
public boolean getZeroHeight() { public boolean getZeroHeight() {
return this.row.getHidden(); return this.row.getHidden();
} }


/**
* Remove the Cell from this row.
*
* @param cell to remove
*/
public void removeCell(Cell cell) { public void removeCell(Cell cell) {
int counter = 0; int counter = 0;
for (Iterator<Cell> it = cellIterator(); it.hasNext(); ) { for (Iterator<Cell> it = cellIterator(); it.hasNext(); ) {
Cell c = it.next(); Cell c = it.next();
if (c.getCellNum() == cell.getCellNum()) {
if (c.getColumnIndex() == cell.getColumnIndex()) {
it.remove(); it.remove();
row.removeC(counter); row.removeC(counter);
continue; continue;
setHeight((short)(height*20)); setHeight((short)(height*20));
} }


/**
* Set the row number of this row.
*
* @param rowNum the row number (0-based)
*/
public void setRowNum(int rowNum) { public void setRowNum(int rowNum) {
this.row.setR(rowNum + 1); this.row.setR(rowNum + 1);


} }


/**
* Set whether or not to display this row with 0 height
*
* @param height height is zero or not.
*/
public void setZeroHeight(boolean height) { public void setZeroHeight(boolean height) {
this.row.setHidden(height); this.row.setHidden(height);


} }
/**
* Returns the underlying CTRow xml bean representing this row
*
* @return the underlying CTRow bean
*/
public CTRow getCTRow(){ public CTRow getCTRow(){
return this.row; return this.row;
} }

+ 44
- 51
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java View File



protected CTSheet sheet; protected CTSheet sheet;
protected CTWorksheet worksheet; protected CTWorksheet worksheet;
protected CTDialogsheet dialogsheet;
protected List<Row> rows; protected List<Row> rows;
protected List<XSSFHyperlink> hyperlinks; protected List<XSSFHyperlink> hyperlinks;
protected ColumnHelper columnHelper; protected ColumnHelper columnHelper;
private CommentsSource sheetComments; private CommentsSource sheetComments;
protected CTMergeCells ctMergeCells;

public static final short LeftMargin = 0;
public static final short RightMargin = 1;
public static final short TopMargin = 2;
public static final short BottomMargin = 3;
public static final short HeaderMargin = 4;
public static final short FooterMargin = 5;



public XSSFSheet() { public XSSFSheet() {
super(null, null); super(null, null);




public int addMergedRegion(Region region) { public int addMergedRegion(Region region) {
addNewMergeCell(region);
CTMergeCells ctMergeCells = worksheet.isSetMergeCells() ? worksheet.getMergeCells() : worksheet.addNewMergeCells();
CTMergeCell ctMergeCell = ctMergeCells.addNewMergeCell();
ctMergeCell.setRef(region.getRegionRef());
return ctMergeCells.sizeOfMergeCellArray(); return ctMergeCells.sizeOfMergeCellArray();
} }


* @param useMergedCells whether to use the contents of merged cells when calculating the width of the column * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
*/ */
public void autoSizeColumn(short column, boolean useMergedCells) { public void autoSizeColumn(short column, boolean useMergedCells) {
//TODO:
columnHelper.setColBestFit(column, true);
double width = ColumnHelper.getColumnWidth(this, column, useMergedCells);
if(width != -1){
columnHelper.setColBestFit(column, true);
columnHelper.setCustomWidth(column, true);
columnHelper.setColWidth(column, width);
}
} }


/** /**
worksheet.addNewSheetFormatPr(); worksheet.addNewSheetFormatPr();
} }


public boolean getDialog() {
if (dialogsheet != null) {
return true;
}
return false;
}


/** /**
* Get whether to display the guts or not, * Get whether to display the guts or not,
* default value is true * default value is true
} }


public Region getMergedRegionAt(int index) { public Region getMergedRegionAt(int index) {
CTMergeCell ctMergeCell = getMergedCells().getMergeCellArray(index);
CTMergeCells ctMergeCells = worksheet.getMergeCells();
if(ctMergeCells == null) throw new IllegalStateException("This worksheet does not contain merged regions");

CTMergeCell ctMergeCell = ctMergeCells.getMergeCellArray(index);
return new Region(ctMergeCell.getRef()); return new Region(ctMergeCell.getRef());
} }


/**
* @return the merged region at the specified index
*/
public CellRangeAddress getMergedRegion(int index) {
CTMergeCells ctMergeCells = worksheet.getMergeCells();
if(ctMergeCells == null) throw new IllegalStateException("This worksheet does not contain merged regions");

CTMergeCell ctMergeCell = ctMergeCells.getMergeCellArray(index);
String ref = ctMergeCell.getRef();
CellReference cell1 = new CellReference(ref.substring(0, ref.indexOf(":")));
CellReference cell2 = new CellReference(ref.substring(ref.indexOf(":") + 1));
return new CellRangeAddress(cell1.getRow(), cell2.getRow(), cell1.getCol(), cell2.getCol());
}

public int getNumMergedRegions() { public int getNumMergedRegions() {
return getMergedCells().sizeOfMergeCellArray();
CTMergeCells ctMergeCells = worksheet.getMergeCells();
return ctMergeCells == null ? 0 : ctMergeCells.sizeOfMergeCellArray();
} }


public int getNumHyperlinks() { public int getNumHyperlinks() {


} }


/**
* Removes a merged region of cells (hence letting them free)
*
* @param index of the region to unmerge
*/
public void removeMergedRegion(int index) { public void removeMergedRegion(int index) {
CTMergeCell[] mergeCellsArray = new CTMergeCell[getMergedCells().sizeOfMergeCellArray() - 1];
for (int i = 0 ; i < getMergedCells().sizeOfMergeCellArray() ; i++) {
CTMergeCells ctMergeCells = worksheet.getMergeCells();

CTMergeCell[] mergeCellsArray = new CTMergeCell[ctMergeCells.sizeOfMergeCellArray() - 1];
for (int i = 0 ; i < ctMergeCells.sizeOfMergeCellArray() ; i++) {
if (i < index) { if (i < index) {
mergeCellsArray[i] = getMergedCells().getMergeCellArray(i);
mergeCellsArray[i] = ctMergeCells.getMergeCellArray(i);
} }
else if (i > index) { else if (i > index) {
mergeCellsArray[i - 1] = getMergedCells().getMergeCellArray(i);
mergeCellsArray[i - 1] = ctMergeCells.getMergeCellArray(i);
} }
} }
getMergedCells().setMergeCellArray(mergeCellsArray);
ctMergeCells.setMergeCellArray(mergeCellsArray);
} }


public void removeRow(Row row) { public void removeRow(Row row) {


} }


public void setDialog(boolean b) {
if(b && dialogsheet == null){
CTDialogsheet dialogSheet = CTDialogsheet.Factory.newInstance();
dialogsheet = dialogSheet;
}else{
dialogsheet = null;
}
}

/** /**
* Sets the flag indicating whether this sheet should display formulas. * Sets the flag indicating whether this sheet should display formulas.
* *
return sheetComments; return sheetComments;
} }


private void addNewMergeCell(Region region) {
ctMergeCells = getMergedCells();
CTMergeCell ctMergeCell = ctMergeCells.addNewMergeCell();
ctMergeCell.setRef(region.getRegionRef());
}

private CTMergeCells getMergedCells() {
if (ctMergeCells == null) {
ctMergeCells = worksheet.addNewMergeCells();
}
return ctMergeCells;
}

private CTPageSetUpPr getSheetTypePageSetUpPr() { private CTPageSetUpPr getSheetTypePageSetUpPr() {
CTSheetPr sheetPr = getSheetTypeSheetPr(); CTSheetPr sheetPr = getSheetTypeSheetPr();
return sheetPr.isSetPageSetUpPr() ? sheetPr.getPageSetUpPr() : sheetPr.addNewPageSetUpPr(); return sheetPr.isSetPageSetUpPr() ? sheetPr.getPageSetUpPr() : sheetPr.addNewPageSetUpPr();


if(worksheet.getColsArray().length == 1) { if(worksheet.getColsArray().length == 1) {
CTCols col = worksheet.getColsArray(0); CTCols col = worksheet.getColsArray(0);
if(col.getColArray().length == 0) {
CTCol[] cols = col.getColArray();
if(cols.length == 0) {
worksheet.setColsArray(null); worksheet.setColsArray(null);
} }
} }

// Now re-generate our CTHyperlinks, if needed // Now re-generate our CTHyperlinks, if needed
if(hyperlinks.size() > 0) { if(hyperlinks.size() > 0) {
if(worksheet.getHyperlinks() == null) { if(worksheet.getHyperlinks() == null) {

+ 11
- 36
src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java View File

*/ */
public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<XSSFSheet> { public class XSSFWorkbook extends POIXMLDocument implements Workbook, Iterable<XSSFSheet> {


/**
* Width of one character of the default font in pixels. Same for Calibry and Arial.
*/
public static final float DEFAULT_CHARACTER_WIDTH = 7.0017f;

/** /**
* The underlying XML bean * The underlying XML bean
*/ */
*/ */
private static Package ensureWriteAccess(Package pkg) throws IOException { private static Package ensureWriteAccess(Package pkg) throws IOException {
if(pkg.getPackageAccess() == PackageAccess.READ){ if(pkg.getPackageAccess() == PackageAccess.READ){
//YK: current implementation of OpenXML4J is funny.
try { try {
return PackageHelper.clone(pkg); return PackageHelper.clone(pkg);
} catch (OpenXML4JException e){ } catch (OpenXML4JException e){
xf.setBorderId(0); xf.setBorderId(0);
xf.setXfId(0); xf.setXfId(0);
int xfSize=(stylesSource)._getStyleXfsSize(); int xfSize=(stylesSource)._getStyleXfsSize();
long indexXf=(stylesSource).putCellXf(xf);
XSSFCellStyle style = new XSSFCellStyle(new Long(indexXf-1).intValue(), xfSize-1, stylesSource);
int indexXf=(stylesSource).putCellXf(xf);
XSSFCellStyle style = new XSSFCellStyle(indexXf-1, xfSize-1, stylesSource);
return style; return style;
} }


return pictures; return pictures;
} }


public boolean getBackupFlag() {
// TODO Auto-generated method stub
return false;
}

public XSSFCellStyle getCellStyleAt(short idx) { public XSSFCellStyle getCellStyleAt(short idx) {
return stylesSource.getStyleAt(idx); return stylesSource.getStyleAt(idx);
} }
* @return String Null if no print area has been defined * @return String Null if no print area has been defined
*/ */
public String getPrintArea(int sheetIndex) { public String getPrintArea(int sheetIndex) {
XSSFName name = getSpecificBuiltinRecord(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
if (name == null) return null; if (name == null) return null;
//adding one here because 0 indicates a global named region; doesnt make sense for print areas //adding one here because 0 indicates a global named region; doesnt make sense for print areas
return name.getReference(); return name.getReference();
} }
} }


public void setBackupFlag(boolean backupValue) {
// TODO Auto-generated method stub

}

/** /**
* Gets the first tab that is displayed in the list of tabs in excel. * Gets the first tab that is displayed in the list of tabs in excel.
* *
* @param reference Valid name Reference for the Print Area * @param reference Valid name Reference for the Print Area
*/ */
public void setPrintArea(int sheetIndex, String reference) { public void setPrintArea(int sheetIndex, String reference) {
XSSFName name = getSpecificBuiltinRecord(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
if (name == null) { if (name == null) {
name = createBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex); name = createBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex);
namedRanges.add(name); namedRanges.add(name);
} }




public XSSFName getSpecificBuiltinRecord(String builtInCode, int sheetNumber) {
private XSSFName getBuiltInName(String builtInCode, int sheetNumber) {
for (XSSFName name : namedRanges) { for (XSSFName name : namedRanges) {
if (name.getNameName().equalsIgnoreCase(builtInCode) && name.getLocalSheetId() == sheetNumber) { if (name.getNameName().equalsIgnoreCase(builtInCode) && name.getLocalSheetId() == sheetNumber) {
return name; return name;
* Generates a NameRecord to represent a built-in region * Generates a NameRecord to represent a built-in region
* @return a new NameRecord * @return a new NameRecord
*/ */
public XSSFName createBuiltInName(String builtInName, int sheetNumber) {
private XSSFName createBuiltInName(String builtInName, int sheetNumber) {
if (sheetNumber < 0 || sheetNumber+1 > Short.MAX_VALUE) { if (sheetNumber < 0 || sheetNumber+1 > Short.MAX_VALUE) {
throw new IllegalArgumentException("Sheet number ["+sheetNumber+"]is not valid "); throw new IllegalArgumentException("Sheet number ["+sheetNumber+"]is not valid ");
} }
nameRecord.setLocalSheetId(sheetNumber); nameRecord.setLocalSheetId(sheetNumber);
XSSFName name=new XSSFName(nameRecord,this); XSSFName name=new XSSFName(nameRecord,this);
//while(namedRanges.contains(name)) {
for(XSSFName nr : namedRanges){ for(XSSFName nr : namedRanges){
if(nr.equals(name)) if(nr.equals(name))
throw new RuntimeException("Builtin (" + builtInName throw new RuntimeException("Builtin (" + builtInName
newcts.set(cts); newcts.set(cts);
} }


public void unwriteProtectWorkbook() {
// TODO Auto-generated method stub

}

/** /**
* marshal named ranges from the {@link #namedRanges} collection to the underlying CTWorkbook bean * marshal named ranges from the {@link #namedRanges} collection to the underlying CTWorkbook bean
*/ */
getPackage().save(stream); getPackage().save(stream);
} }


public void writeProtectWorkbook(String password, String username) {
// TODO Auto-generated method stub

}

/** /**
* Returns SharedStringsTable - tha cache of string for this workbook * Returns SharedStringsTable - tha cache of string for this workbook
* *
public SharedStringsTable getSharedStringSource() { public SharedStringsTable getSharedStringSource() {
return this.sharedStringSource; return this.sharedStringSource;
} }
//TODO do we really need setSharedStringSource?
protected void setSharedStringSource(SharedStringsTable sharedStringSource) {
this.sharedStringSource = sharedStringSource;
}


/** /**
* Return a object representing a collection of shared objects used for styling content, * Return a object representing a collection of shared objects used for styling content,
public StylesTable getStylesSource() { public StylesTable getStylesSource() {
return this.stylesSource; return this.stylesSource;
} }
//TODO do we really need setStylesSource?
protected void setStylesSource(StylesTable stylesSource) {
this.stylesSource = stylesSource;
}


/** /**
* Returns an object that handles instantiating concrete * Returns an object that handles instantiating concrete

+ 174
- 0
src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java View File

package org.apache.poi.xssf.usermodel.helpers; package org.apache.poi.xssf.usermodel.helpers;


import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator;
import java.text.AttributedString;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.awt.font.TextLayout;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;


import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.util.CTColComparator; import org.apache.poi.xssf.util.CTColComparator;
import org.apache.poi.xssf.util.NumericRanges; import org.apache.poi.xssf.util.NumericRanges;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
CTCol col = getOrCreateColumn1Based(index+1, false); CTCol col = getOrCreateColumn1Based(index+1, false);
col.setBestFit(bestFit); col.setBestFit(bestFit);
} }
public void setCustomWidth(long index, boolean bestFit) {
CTCol col = getOrCreateColumn1Based(index+1, false);
col.setCustomWidth(bestFit);
}


public void setColWidth(long index, double width) { public void setColWidth(long index, double width) {
CTCol col = getOrCreateColumn1Based(index+1, false); CTCol col = getOrCreateColumn1Based(index+1, false);
} }
return -1; return -1;
} }

public static double getColumnWidth(XSSFSheet sheet, int column, boolean useMergedCells){
AttributedString str;
TextLayout layout;
/**
* Excel measures columns in units of 1/256th of a character width
* but the docs say nothing about what particular character is used.
* '0' looks to be a good choice.
*/
char defaultChar = '0';

/**
* This is the multiple that the font height is scaled by when determining the
* boundary of rotated text.
*/
double fontHeightMultiple = 2.0;

FontRenderContext frc = new FontRenderContext(null, true, true);

XSSFWorkbook wb = sheet.getWorkbook();
XSSFFont defaultFont = wb.getFontAt((short) 0);

str = new AttributedString("" + defaultChar);
copyAttributes(defaultFont, str, 0, 1);
layout = new TextLayout(str.getIterator(), frc);
int defaultCharWidth = (int)layout.getAdvance();

double width = -1;
rows:
for (Iterator it = sheet.rowIterator(); it.hasNext();) {
XSSFRow row = (XSSFRow) it.next();
XSSFCell cell = row.getCell(column);

if (cell == null) {
continue;
}

int colspan = 1;
for (int i = 0 ; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i);
if (containsCell(region, row.getRowNum(), column)) {
if (!useMergedCells) {
// If we're not using merged cells, skip this one and move on to the next.
continue rows;
}
cell = row.getCell(region.getFirstColumn());
colspan = 1 + region.getLastColumn() - region.getFirstColumn();
}
}

XSSFCellStyle style = cell.getCellStyle();
XSSFFont font = wb.getFontAt(style.getFontIndex());

if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
XSSFRichTextString rt = cell.getRichStringCellValue();
String[] lines = rt.getString().split("\\n");
for (int i = 0; i < lines.length; i++) {
String txt = lines[i] + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());

if (rt.numFormattingRuns() > 0) {
int pos = 0;
for (int j = 0; j < rt.numFormattingRuns(); j++) {
XSSFFont fnt = rt.getFontOfFormattingRun(j);
if (fnt != null) {
int len = rt.getLengthOfFormattingRun(j);
copyAttributes(fnt, str, pos, pos + len);
pos += len;
}
}
}

layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
} else {
String sval = null;
if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
String format = style.getDataFormatString().replaceAll("\"", "");
double value = cell.getNumericCellValue();
try {
NumberFormat fmt;
if ("General".equals(format))
sval = "" + value;
else
{
fmt = new DecimalFormat(format);
sval = fmt.format(value);
}
} catch (Exception e) {
sval = "" + value;
}
} else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
sval = String.valueOf(cell.getBooleanCellValue());
}
if(sval != null) {
String txt = sval + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());

layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
}

}
return width;
}

/**
* Copy text attributes from the supplied HSSFFont to Java2D AttributedString
*/
private static void copyAttributes(XSSFFont font, AttributedString str, int startIdx, int endIdx) {
str.addAttribute(TextAttribute.FAMILY, font.getFontName(), startIdx, endIdx);
str.addAttribute(TextAttribute.SIZE, new Float(font.getFontHeightInPoints()));
if (font.getBoldweight() == XSSFFont.BOLDWEIGHT_BOLD) str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx);
if (font.getItalic() ) str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx);
if (font.getUnderline() == XSSFFont.U_SINGLE ) str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx);
}

private static boolean containsCell(CellRangeAddress cr, int rowIx, int colIx) {
if (cr.getFirstRow() <= rowIx && cr.getLastRow() >= rowIx
&& cr.getFirstColumn() <= colIx && cr.getLastColumn() >= colIx)
{
return true;
}
return false;
}

} }

+ 4
- 11
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java View File



package org.apache.poi.xssf.usermodel; package org.apache.poi.xssf.usermodel;


import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;


import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.CommentsTable;
import org.apache.poi.xssf.model.SharedStringSource;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;


CellStyle cs = workbook.createCellStyle(); CellStyle cs = workbook.createCellStyle();
assertNotNull(cs); assertNotNull(cs);
assertTrue(cs.getIndex() > 0);

assertNotNull(creationHelper); assertNotNull(creationHelper);
assertNotNull(creationHelper.createDataFormat()); assertNotNull(creationHelper.createDataFormat());
creationHelper.createDataFormat().getFormat("yyyy/mm/dd") creationHelper.createDataFormat().getFormat("yyyy/mm/dd")
); );
Cell cell = sheet.createRow(0).createCell((short)0); Cell cell = sheet.createRow(0).createCell((short)0);
assertNotNull(cell.getCellStyle());
assertEquals(0, cell.getCellStyle().getIndex());
cell.setCellValue(new Date(654321)); cell.setCellValue(new Date(654321));
assertNull(cell.getCellStyle());
cell.setCellStyle(cs); cell.setCellStyle(cs);
assertEquals(new Date(654321), cell.getDateCellValue()); assertEquals(new Date(654321), cell.getDateCellValue());

+ 4
- 4
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java View File



public void testGetSetIndent() { public void testGetSetIndent() {
assertEquals((short)0, cellStyle.getIndention()); assertEquals((short)0, cellStyle.getIndention());
cellXf.getAlignment().setIndent(3);
cellStyle.setIndention((short)3);
assertEquals((short)3, cellStyle.getIndention()); assertEquals((short)3, cellStyle.getIndention());
cellStyle.setIndention((short) 13); cellStyle.setIndention((short) 13);
assertEquals((short)13, cellXf.getAlignment().getIndent());
assertEquals((short)13, cellStyle.getIndention());
} }


public void testGetSetAlignement() { public void testGetSetAlignement() {


public void testGetSetWrapText() { public void testGetSetWrapText() {
assertFalse(cellStyle.getWrapText()); assertFalse(cellStyle.getWrapText());
cellXf.getAlignment().setWrapText(true);
cellStyle.setWrapText(true);
assertTrue(cellStyle.getWrapText()); assertTrue(cellStyle.getWrapText());
cellStyle.setWrapText(false); cellStyle.setWrapText(false);
assertFalse(cellXf.getAlignment().getWrapText());
assertFalse(cellStyle.getWrapText());
} }


/** /**

+ 1
- 3
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java View File

public void testGetDialog() { public void testGetDialog() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
assertFalse(sheet.getDialog());
XSSFSheet dialogsheet = (XSSFSheet) workbook.createDialogsheet("Dialogsheet 1", null);
XSSFDialogsheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", null);
assertTrue(dialogsheet.getDialog()); assertTrue(dialogsheet.getDialog());
} }

+ 6
- 6
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java View File

assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, XSSFRow.CREATE_NULL_AS_BLANK).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5, XSSFRow.CREATE_NULL_AS_BLANK).getCellType());


// Check created ones get the right column // Check created ones get the right column
assertEquals((short)0, row.getCell(0, XSSFRow.CREATE_NULL_AS_BLANK).getCellNum());
assertEquals((short)1, row.getCell(1, XSSFRow.CREATE_NULL_AS_BLANK).getCellNum());
assertEquals((short)2, row.getCell(2, XSSFRow.CREATE_NULL_AS_BLANK).getCellNum());
assertEquals((short)3, row.getCell(3, XSSFRow.CREATE_NULL_AS_BLANK).getCellNum());
assertEquals((short)4, row.getCell(4, XSSFRow.CREATE_NULL_AS_BLANK).getCellNum());
assertEquals((short)5, row.getCell(5, XSSFRow.CREATE_NULL_AS_BLANK).getCellNum());
assertEquals((short)0, row.getCell(0, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)1, row.getCell(1, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)2, row.getCell(2, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)3, row.getCell(3, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)4, row.getCell(4, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
assertEquals((short)5, row.getCell(5, XSSFRow.CREATE_NULL_AS_BLANK).getColumnIndex());
} }


/** /**

+ 19
- 29
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java View File

import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
XSSFOddFooter ftr; XSSFOddFooter ftr;


// Sheet 1 has a header with center and right text // Sheet 1 has a header with center and right text
XSSFSheet s1 = (XSSFSheet)workbook.getSheetAt(0);
XSSFSheet s1 = workbook.getSheetAt(0);
assertNotNull(s1.getHeader()); assertNotNull(s1.getHeader());
assertNotNull(s1.getFooter()); assertNotNull(s1.getFooter());
hdr = (XSSFOddHeader)s1.getHeader(); hdr = (XSSFOddHeader)s1.getHeader();




// Sheet 2 has a footer, but it's empty // Sheet 2 has a footer, but it's empty
XSSFSheet s2 = (XSSFSheet)workbook.getSheetAt(1);
XSSFSheet s2 = workbook.getSheetAt(1);
assertNotNull(s2.getHeader()); assertNotNull(s2.getHeader());
assertNotNull(s2.getFooter()); assertNotNull(s2.getFooter());
hdr = (XSSFOddHeader)s2.getHeader(); hdr = (XSSFOddHeader)s2.getHeader();


public void testGetAllHeadersFooters() { public void testGetAllHeadersFooters() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertNotNull(sheet.getOddFooter()); assertNotNull(sheet.getOddFooter());
assertNotNull(sheet.getEvenFooter()); assertNotNull(sheet.getEvenFooter());
assertNotNull(sheet.getFirstFooter()); assertNotNull(sheet.getFirstFooter());
public void testAutoSizeColumn() { public void testAutoSizeColumn() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
sheet.createRow(0).createCell(13).setCellValue("test");

sheet.autoSizeColumn((short)13);

ColumnHelper columnHelper = sheet.getColumnHelper(); ColumnHelper columnHelper = sheet.getColumnHelper();
CTCol col = columnHelper.getColumn(13, false); CTCol col = columnHelper.getColumn(13, false);
assertNull(col);
sheet.autoSizeColumn((short)13);
col = columnHelper.getColumn(13, false);
assertNotNull(col);
assertTrue(col.getBestFit());
}
public void testGetDialog() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getDialog());
XSSFSheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", null);
assertTrue(dialogsheet.getDialog());
assertTrue(col.getBestFit());
} }
public void testGetSetHorizontallyCentered() { public void testGetSetHorizontallyCentered() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getHorizontallyCenter()); assertFalse(sheet.getHorizontallyCenter());
sheet.setHorizontallyCenter(true); sheet.setHorizontallyCenter(true);
assertTrue(sheet.getHorizontallyCenter()); assertTrue(sheet.getHorizontallyCenter());
public void testGetSetVerticallyCentered() { public void testGetSetVerticallyCentered() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getVerticallyCenter()); assertFalse(sheet.getVerticallyCenter());
sheet.setVerticallyCenter(true); sheet.setVerticallyCenter(true);
assertTrue(sheet.getVerticallyCenter()); assertTrue(sheet.getVerticallyCenter());
public void testIsSetPrintGridlines() { public void testIsSetPrintGridlines() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.isPrintGridlines()); assertFalse(sheet.isPrintGridlines());
sheet.setPrintGridlines(true); sheet.setPrintGridlines(true);
assertTrue(sheet.isPrintGridlines()); assertTrue(sheet.isPrintGridlines());
public void testIsSetDisplayFormulas() { public void testIsSetDisplayFormulas() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.isDisplayFormulas()); assertFalse(sheet.isDisplayFormulas());
sheet.setDisplayFormulas(true); sheet.setDisplayFormulas(true);
assertTrue(sheet.isDisplayFormulas()); assertTrue(sheet.isDisplayFormulas());
public void testIsSetDisplayGridLines() { public void testIsSetDisplayGridLines() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertTrue(sheet.isDisplayGridlines()); assertTrue(sheet.isDisplayGridlines());
sheet.setDisplayGridlines(false); sheet.setDisplayGridlines(false);
assertFalse(sheet.isDisplayGridlines()); assertFalse(sheet.isDisplayGridlines());
public void testIsSetDisplayGuts() { public void testIsSetDisplayGuts() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertTrue(sheet.getDisplayGuts()); assertTrue(sheet.getDisplayGuts());
sheet.setDisplayGuts(false); sheet.setDisplayGuts(false);
assertFalse(sheet.getDisplayGuts()); assertFalse(sheet.getDisplayGuts());
public void testIsSetDisplayRowColHeadings() { public void testIsSetDisplayRowColHeadings() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertTrue(sheet.isDisplayRowColHeadings()); assertTrue(sheet.isDisplayRowColHeadings());
sheet.setDisplayRowColHeadings(false); sheet.setDisplayRowColHeadings(false);
assertFalse(sheet.isDisplayRowColHeadings()); assertFalse(sheet.isDisplayRowColHeadings());
public void testGetScenarioProtect() { public void testGetScenarioProtect() {
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Sheet 1");
XSSFSheet sheet = workbook.createSheet("Sheet 1");
assertFalse(sheet.getScenarioProtect()); assertFalse(sheet.getScenarioProtect());
} }
sheet.setDefaultColumnStyle((short) 3, cellStyle); sheet.setDefaultColumnStyle((short) 3, cellStyle);
assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle()); assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle());
XSSFRow row = (XSSFRow) sheet.createRow(0);
XSSFCell cell = (XSSFCell) sheet.getRow(0).createCell(3);
XSSFRow row = sheet.createRow(0);
XSSFCell cell = sheet.getRow(0).createCell(3);
} }

+ 1
- 3
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java View File

((XSSFFont)font).setBold(true); ((XSSFFont)font).setBold(true);
font.setUnderline(Font.U_DOUBLE); font.setUnderline(Font.U_DOUBLE);
StylesTable styleSource=new StylesTable(); StylesTable styleSource=new StylesTable();
long index=styleSource.putFont(font);
workbook.setStylesSource(styleSource);
fontFind=workbook.findFont(Font.BOLDWEIGHT_BOLD, IndexedColors.BLACK.getIndex(), (short)15, "Calibri", false, false, Font.SS_NONE, Font.U_DOUBLE); fontFind=workbook.findFont(Font.BOLDWEIGHT_BOLD, IndexedColors.BLACK.getIndex(), (short)15, "Calibri", false, false, Font.SS_NONE, Font.U_DOUBLE);
assertNull(fontFind); assertNull(fontFind);
} }
public void testSetDisplayedTab(){ public void testSetDisplayedTab(){
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
workbook.setFirstVisibleTab(new Integer(1).shortValue());
workbook.setFirstVisibleTab(1);
short i = (short) workbook.getFirstVisibleTab(); short i = (short) workbook.getFirstVisibleTab();
//0 (defualt value) is not longer set //0 (defualt value) is not longer set
assertNotSame(0, i); assertNotSame(0, i);

Loading…
Cancel
Save