boolean ignoreHPSF = (handler instanceof HPSFFileHandler);
try {
- InputStream stream = new BufferedInputStream(new FileInputStream(inputFile), 64*1024);
- try {
+ try (InputStream stream = new BufferedInputStream(new FileInputStream(inputFile), 64 * 1024)) {
handler.handleFile(stream, file);
- assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!",
- OLD_FILES_HWPF.contains(file) && !ignoreHPSF);
- } finally {
- stream.close();
+ assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!",
+ OLD_FILES_HWPF.contains(file) && !ignoreHPSF);
}
handler.handleExtracting(inputFile);
handleExtractingAsStream(file);
if(extractor instanceof POIOLE2TextExtractor) {
- HPSFPropertiesExtractor hpsfExtractor = new HPSFPropertiesExtractor((POIOLE2TextExtractor)extractor);
- try {
- assertNotNull(hpsfExtractor.getDocumentSummaryInformationText());
- assertNotNull(hpsfExtractor.getSummaryInformationText());
- String text = hpsfExtractor.getText();
- //System.out.println(text);
- assertNotNull(text);
- } finally {
- hpsfExtractor.close();
- }
+ try (HPSFPropertiesExtractor hpsfExtractor = new HPSFPropertiesExtractor((POIOLE2TextExtractor) extractor)) {
+ assertNotNull(hpsfExtractor.getDocumentSummaryInformationText());
+ assertNotNull(hpsfExtractor.getSummaryInformationText());
+ String text = hpsfExtractor.getText();
+ //System.out.println(text);
+ assertNotNull(text);
+ }
}
} catch (IllegalArgumentException e) {
if(!EXPECTED_EXTRACTOR_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
}
private void handleExtractingAsStream(File file) throws IOException, OpenXML4JException, XmlException {
- InputStream stream = new FileInputStream(file);
- try {
- POITextExtractor streamExtractor = ExtractorFactory.createExtractor(stream);
- try {
+ try (InputStream stream = new FileInputStream(file)) {
+ try (POITextExtractor streamExtractor = ExtractorFactory.createExtractor(stream)) {
assertNotNull(streamExtractor);
-
+
assertNotNull(streamExtractor.getText());
- } finally {
- streamExtractor.close();
}
- } finally {
- stream.close();
}
}
stream = new FileInputStream(file);
try {
- VisioTextExtractor extractor = new VisioTextExtractor(stream);
- try {
+ try (VisioTextExtractor extractor = new VisioTextExtractor(stream)) {
assertNotNull(extractor.getText());
- } finally {
- extractor.close();
}
} finally {
stream.close();
@Test
public void test() throws Exception {
String path = "test-data/hmef/quick-winmail.dat";
- InputStream stream = new FileInputStream(path);
- try {
+ try (InputStream stream = new FileInputStream(path)) {
handleFile(stream, path);
- } finally {
- stream.close();
}
}
}
stream = new FileInputStream(file);
try {
- PublisherTextExtractor extractor = new PublisherTextExtractor(stream);
- try {
+ try (PublisherTextExtractor extractor = new PublisherTextExtractor(stream)) {
assertNotNull(extractor.getText());
- } finally {
- extractor.close();
}
} finally {
stream.close();
if (!root.hasEntry(streamName)) {
return false;
}
- DocumentInputStream dis = root.createDocumentInputStream(streamName);
- try {
- return PropertySet.isPropertySetStream(dis);
- } finally {
- dis.close();
+ try (DocumentInputStream dis = root.createDocumentInputStream(streamName)) {
+ return PropertySet.isPropertySetStream(dis);
}
}
@Test
public void test() throws Exception {
String path = "test-data/hpsf/Test0313rur.adm";
- InputStream stream = new FileInputStream(path);
- try {
- handleFile(stream, path);
- } finally {
- stream.close();
- }
+ try (InputStream stream = new FileInputStream(path)) {
+ handleFile(stream, path);
+ }
}
// a test-case to test this locally without executing the full TestAllFiles
@Override
@Test
public void test() throws Exception {
- File[] files = new File("test-data/slideshow/").listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".ppt");
- }
- });
+ File[] files = new File("test-data/slideshow/").listFiles((dir, name) -> name.endsWith(".ppt"));
assertNotNull(files);
System.out.println("Testing " + files.length + " files");
System.out.println(file);
//System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger");
- InputStream stream = new FileInputStream(file);
- try {
+ try (InputStream stream = new FileInputStream(file)) {
handleFile(stream, file.getPath());
- } finally {
- stream.close();
}
handleExtracting(file);
public static void main(String[] args) throws Exception {
System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger");
- InputStream stream = new FileInputStream(args[0]);
- try {
+ try (InputStream stream = new FileInputStream(args[0])) {
new HSLFFileHandler().handleFile(stream, args[0]);
- } finally {
- stream.close();
}
}
}
@Test
public void test() throws Exception {
File file = new File("test-data/hsmf/logsat.com_signatures_valid.msg");
- InputStream stream = new FileInputStream(file);
- try {
+ try (InputStream stream = new FileInputStream(file)) {
handleFile(stream, file.getPath());
- } finally {
- stream.close();
}
handleExtracting(file);
public void test() throws Exception {
File file = new File("test-data/diagram/test.vsdx");
- InputStream stream = new PushbackInputStream(new FileInputStream(file), 100000);
- try {
- handleFile(stream, file.getPath());
- } finally {
- stream.close();
- }
+ try (InputStream stream = new PushbackInputStream(new FileInputStream(file), 100000)) {
+ handleFile(stream, file.getPath());
+ }
handleExtracting(file);
}
@Override
public void handleFile(InputStream stream, String path) throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(stream);
- try {
- handlePOIFSFileSystem(fs);
- handleHPSFProperties(fs);
- } finally {
- fs.close();
- }
+ try (POIFSFileSystem fs = new POIFSFileSystem(stream)) {
+ handlePOIFSFileSystem(fs);
+ handleHPSFProperties(fs);
+ }
}
private void handleHPSFProperties(POIFSFileSystem fs) throws IOException {
- HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs);
- try {
+ try (HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) {
// can be null
ext.getDocSummaryInformation();
ext.getSummaryInformation();
-
+
assertNotNull(ext.getDocumentSummaryInformationText());
assertNotNull(ext.getSummaryInformationText());
assertNotNull(ext.getText());
- } finally {
- ext.close();
}
}
public void test() throws Exception {
File file = new File("test-data/poifs/Notes.ole2");
- InputStream stream = new FileInputStream(file);
- try {
+ try (InputStream stream = new FileInputStream(file)) {
handleFile(stream, file.getPath());
- } finally {
- stream.close();
}
//handleExtracting(file);
readContent(ss);
// read in the written file
- SlideShow<?,?> read = SlideShowFactory.create(new ByteArrayInputStream(out.toByteArray()));
- try {
+ try (SlideShow<?, ?> read = SlideShowFactory.create(new ByteArrayInputStream(out.toByteArray()))) {
assertNotNull(read);
readContent(read);
- } finally {
- read.close();
}
}
// a test-case to test this locally without executing the full TestAllFiles
@Test
public void test() throws Exception {
- OPCPackage pkg = OPCPackage.open("test-data/diagram/test.vsdx", PackageAccess.READ);
- try {
+ try (OPCPackage pkg = OPCPackage.open("test-data/diagram/test.vsdx", PackageAccess.READ)) {
XmlVisioDocument doc = new XmlVisioDocument(pkg);
new POIXMLDocumentHandler().handlePOIXMLDocument(doc);
- } finally {
- pkg.close();
}
}
}
\ No newline at end of file
// additionally try the other getText() methods
-
- XSLFPowerPointExtractor extractor = (XSLFPowerPointExtractor) ExtractorFactory.createExtractor(file);
- try {
- assertNotNull(extractor);
- assertNotNull(extractor.getText(true, true, true));
- assertEquals("With all options disabled we should not get text",
- "", extractor.getText(false, false, false));
- } finally {
- extractor.close();
- }
+ try (XSLFPowerPointExtractor extractor = (XSLFPowerPointExtractor) ExtractorFactory.createExtractor(file)) {
+ assertNotNull(extractor);
+
+ assertNotNull(extractor.getText(true, true, true));
+ assertEquals("With all options disabled we should not get text",
+ "", extractor.getText(false, false, false));
+ }
}
// a test-case to test this locally without executing the full TestAllFiles
@Test
public void test() throws Exception {
File file = new File("test-data/slideshow/ae.ac.uaeu.faculty_nafaachbili_GeomLec1.pptx");
- InputStream stream = new FileInputStream(file);
- try {
+ try (InputStream stream = new FileInputStream(file)) {
handleFile(stream, file.getPath());
- } finally {
- stream.close();
}
handleExtracting(file);
IOUtils.copy(stream, out);
final byte[] bytes = out.toByteArray();
- OPCPackage opcPackage = OPCPackage.open(new ByteArrayInputStream(bytes));
- try {
+ try (OPCPackage opcPackage = OPCPackage.open(new ByteArrayInputStream(bytes))) {
testOne(opcPackage);
- } finally {
- opcPackage.close();
}
testNotHandledByWorkbookException(OPCPackage.open(new ByteArrayInputStream(bytes)));
@Test
public void testLocal() throws Exception {
File file = new File("test-data/spreadsheet/Simple.xlsb");
- FileInputStream stream = new FileInputStream(file);
- try {
+ try (FileInputStream stream = new FileInputStream(file)) {
handleFile(stream, file.getPath());
- } finally {
- stream.close();
}
handleExtracting(file);
}
} catch (OLE2NotOfficeXmlFileException e) {
// we have some files that are not actually OOXML and thus cannot be tested here
- } catch (IllegalArgumentException e) {
- if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
- throw e;
- }
- } catch (InvalidFormatException e) {
- if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
- throw e;
- }
- } catch (IOException e) {
- if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
- throw e;
- }
- } catch (POIXMLException e) {
+ } catch (IllegalArgumentException | InvalidFormatException | POIXMLException | IOException e) {
if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
throw e;
}
public void test() throws Exception {
File file = new File("test-data/spreadsheet/ref-56737.xlsx");
- InputStream stream = new BufferedInputStream(new FileInputStream(file));
- try {
+ try (InputStream stream = new BufferedInputStream(new FileInputStream(file))) {
handleFile(stream, file.getPath());
- } finally {
- stream.close();
}
handleExtracting(file);
public void test() throws Exception {
File file = new File("test-data/document/51921-Word-Crash067.docx");
- InputStream stream = new BufferedInputStream(new FileInputStream(file));
- try {
+ try (InputStream stream = new BufferedInputStream(new FileInputStream(file))) {
handleFile(stream, file.getPath());
- } finally {
- stream.close();
}
handleExtracting(file);
return peekedBytes;
}
-
-
-
+
/**
* Reads all the data from the input stream, and returns the bytes read.
+ *
+ * @param stream The byte stream of data to read.
+ * @return A byte array with the read bytes.
+ * @throws IOException If reading data fails or EOF is encountered too early for the given length.
*/
public static byte[] toByteArray(InputStream stream) throws IOException {
return toByteArray(stream, Integer.MAX_VALUE);
/**
* Reads up to {@code length} bytes from the input stream, and returns the bytes read.
+ *
+ * @param stream The byte stream of data to read.
+ * @param length The maximum length to read, use Integer.MAX_VALUE to read the stream
+ * until EOF.
+ * @return A byte array with the read bytes.
+ * @throws IOException If reading data fails or EOF is encountered too early for the given length.
*/
public static byte[] toByteArray(InputStream stream, int length) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Integer.MAX_VALUE ? 4096 : length);
*
* @param format
* @return the next free ImageNumber
- * @throws InvalidFormatException
+ * @throws InvalidFormatException If the format of the picture is not known.
*/
public int getNextPicNameNumber(int format) throws InvalidFormatException {
int img = getAllPackagePictures().size() + 1;
* @param pictureData The picture data
* @param format The format of the picture.
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
- * @throws InvalidFormatException
+ * @throws InvalidFormatException If the format of the picture is not known.
*/
public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException {
XWPFPictureData xwpfPicData = document.findPackagePictureData(pictureData, format);
* @param is The stream to read image from
* @param format The format of the picture.
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} .
- * @throws InvalidFormatException
- * @throws IOException
+ * @throws InvalidFormatException If the format of the picture is not known.
+ * @throws IOException If reading the picture-data from the stream fails.
*/
public String addPictureData(InputStream is, int format) throws InvalidFormatException, IOException {
byte[] data = IOUtils.toByteArray(is);
this.run = r;
this.parent = p;
- /**
+ /*
* reserve already occupied drawing ids, so reserving new ids later will
* not corrupt the document
*/
*/
public boolean isBold() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetB()) {
- return false;
- }
- return isCTOnOff(pr.getB());
+ return pr != null && pr.isSetB() && isCTOnOff(pr.getB());
}
/**
*/
public boolean isItalic() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetI())
- return false;
- return isCTOnOff(pr.getI());
+ return pr != null && pr.isSetI() && isCTOnOff(pr.getI());
}
/**
*/
public boolean isStrikeThrough() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetStrike())
- return false;
- return isCTOnOff(pr.getStrike());
+ return pr != null && pr.isSetStrike() && isCTOnOff(pr.getStrike());
}
/**
*/
public boolean isDoubleStrikeThrough() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetDstrike())
- return false;
- return isCTOnOff(pr.getDstrike());
+ return pr != null && pr.isSetDstrike() && isCTOnOff(pr.getDstrike());
}
/**
public boolean isSmallCaps() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetSmallCaps())
- return false;
- return isCTOnOff(pr.getSmallCaps());
+ return pr != null && pr.isSetSmallCaps() && isCTOnOff(pr.getSmallCaps());
}
public void setSmallCaps(boolean value) {
public boolean isCapitalized() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetCaps())
- return false;
- return isCTOnOff(pr.getCaps());
+ return pr != null && pr.isSetCaps() && isCTOnOff(pr.getCaps());
}
public void setCapitalized(boolean value) {
public boolean isShadowed() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetShadow())
- return false;
- return isCTOnOff(pr.getShadow());
+ return pr != null && pr.isSetShadow() && isCTOnOff(pr.getShadow());
}
public void setShadow(boolean value) {
public boolean isImprinted() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetImprint())
- return false;
- return isCTOnOff(pr.getImprint());
+ return pr != null && pr.isSetImprint() && isCTOnOff(pr.getImprint());
}
public void setImprinted(boolean value) {
public boolean isEmbossed() {
CTRPr pr = run.getRPr();
- if (pr == null || !pr.isSetEmboss())
- return false;
- return isCTOnOff(pr.getEmboss());
+ return pr != null && pr.isSetEmboss() && isCTOnOff(pr.getEmboss());
}
public void setEmbossed(boolean value) {
* the contents of this run.
* </p>
*
- * @param valign
+ * @param valign Type of vertical align to apply
* @see VerticalAlign
*/
public void setSubscript(VerticalAlign valign) {
* <p>
* Also sets the other font ranges, if they haven't been set before
*
- * @param fontFamily
+ * @param fontFamily The font family to apply
* @see FontCharRange
*/
public void setFontFamily(String fontFamily) {
* ascii font char range with the given font family and also set all not
* specified font ranges
*
- * @param fontFamily
+ * @param fontFamily The font family to apply
* @param fcr FontCharRange or null for default handling
*/
public void setFontFamily(String fontFamily, FontCharRange fcr) {
* be used for non complex script characters.
* </p>
*
- * @param size
+ * @param size The font size as number of point measurements.
*/
public void setFontSize(int size) {
BigInteger bint = new BigInteger("" + size);
* contents of this run.
* </p>
*
- * @param val
+ * @param val Positive values will raise the baseline of the text, negative
+ * values will lower it.
*/
public void setTextPosition(int val) {
BigInteger bint = new BigInteger("" + val);
* @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG}
* @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
* @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units}
- * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException
- * @throws IOException
+ * @throws InvalidFormatException If the format of the picture is not known.
+ * @throws IOException If reading the picture-data from the stream fails.
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT
XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
pictures.add(xwpfPicture);
return xwpfPicture;
- } catch (XmlException e) {
- throw new IllegalStateException(e);
- } catch (SAXException e) {
+ } catch (XmlException | SAXException e) {
throw new IllegalStateException(e);
}
}
import java.io.FileInputStream;
import java.io.IOException;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hwpf.converter.AbstractWordUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
+import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.Beta;
-import org.apache.poi.util.IOUtils;
/**
* Common class for {@link ExcelToFoUtils} and {@link ExcelToHtmlUtils}
* @since POI 3.8 beta 5
*/
@Beta
-public class AbstractExcelUtils
-{
+public class AbstractExcelUtils {
/*package*/ static final String EMPTY = "";
private static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
private static final int UNIT_OFFSET_LENGTH = 7;
- public static String getAlign( HorizontalAlignment alignment )
- {
- switch ( alignment )
- {
+ public static String getAlign( HorizontalAlignment alignment ) {
+ switch ( alignment ) {
case CENTER:
return "center";
case CENTER_SELECTION:
}
}
- public static String getBorderStyle( BorderStyle xlsBorder )
- {
+ public static String getBorderStyle( BorderStyle xlsBorder ) {
final String borderStyle;
- switch ( xlsBorder )
- {
+ switch ( xlsBorder ) {
case NONE:
borderStyle = "none";
break;
return borderStyle;
}
- public static String getBorderWidth( BorderStyle xlsBorder )
- {
+ public static String getBorderWidth( BorderStyle xlsBorder ) {
final String borderWidth;
- switch ( xlsBorder )
- {
+ switch ( xlsBorder ) {
case MEDIUM_DASH_DOT:
case MEDIUM_DASH_DOT_DOT:
case MEDIUM_DASHED:
return borderWidth;
}
- public static String getColor( HSSFColor color )
- {
+ public static String getColor( HSSFColor color ) {
StringBuilder stringBuilder = new StringBuilder( 7 );
stringBuilder.append( '#' );
- for ( short s : color.getTriplet() )
- {
+ for ( short s : color.getTriplet() ) {
if ( s < 10 )
stringBuilder.append( '0' );
* "http://apache-poi.1045710.n5.nabble.com/Excel-Column-Width-Unit-Converter-pixels-excel-column-width-units-td2301481.html"
* >here</a> for Xio explanation and details
*/
- public static int getColumnWidthInPx( int widthUnits )
- {
+ public static int getColumnWidthInPx( int widthUnits ) {
int pixels = ( widthUnits / EXCEL_COLUMN_WIDTH_FACTOR )
* UNIT_OFFSET_LENGTH;
/**
* @param mergedRanges
* map of sheet merged ranges built with
- * {@link ExcelToHtmlUtils#buildMergedRangesMap(HSSFSheet)}
+ * {@link ExcelToHtmlUtils#buildMergedRangesMap(Sheet)}
* @return {@link CellRangeAddress} from map if cell with specified row and
* column numbers contained in found range, <tt>null</tt> otherwise
*/
public static CellRangeAddress getMergedRange(
- CellRangeAddress[][] mergedRanges, int rowNumber, int columnNumber )
- {
+ CellRangeAddress[][] mergedRanges, int rowNumber, int columnNumber ) {
CellRangeAddress[] mergedRangeRowInfo = rowNumber < mergedRanges.length ? mergedRanges[rowNumber]
: null;
return !isEmpty( str );
}
- public static HSSFWorkbook loadXls( File xlsFile ) throws IOException
- {
- final FileInputStream inputStream = new FileInputStream( xlsFile );
- try
- {
+ public static HSSFWorkbook loadXls(File xlsFile ) throws IOException {
+ try (final FileInputStream inputStream = new FileInputStream( xlsFile )) {
return new HSSFWorkbook( inputStream );
}
- finally
- {
- IOUtils.closeQuietly( inputStream );
- }
}
-
}
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
* @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Beta
-public class ExcelToHtmlConverter extends AbstractExcelConverter
-{
-
+public class ExcelToHtmlConverter extends AbstractExcelConverter {
private static final POILogger logger = POILogFactory
.getLogger( ExcelToHtmlConverter.class );
* </p>
* Where infile is an input .xls file ( Word 97-2007) which will be rendered
* as HTML into outfile
- * @throws TransformerException
- * @throws Exception
*/
- public static void main( String[] args )
- throws IOException, ParserConfigurationException, TransformerException
- {
- if ( args.length < 2 )
- {
- System.err
- .println( "Usage: ExcelToHtmlConverter <inputFile.xls> <saveTo.html>" );
+ public static void main( String[] args ) throws Exception {
+ if ( args.length < 2 ) {
+ System.err.println( "Usage: ExcelToHtmlConverter <inputFile.xls> <saveTo.html>" );
return;
}
* @param xlsFile
* workbook file to process
* @return DOM representation of result HTML
- * @throws IOException
- * @throws ParserConfigurationException
+ * @throws IOException If an error occurs reading or writing files
+ * @throws ParserConfigurationException If configuration is incorrect
*/
- public static Document process( File xlsFile ) throws IOException, ParserConfigurationException
- {
- final HSSFWorkbook workbook = ExcelToHtmlUtils.loadXls( xlsFile );
- try {
- return ExcelToHtmlConverter.process( workbook );
- } finally {
- workbook.close();
+ public static Document process( File xlsFile ) throws IOException, ParserConfigurationException {
+ try (HSSFWorkbook workbook = ExcelToHtmlUtils.loadXls(xlsFile)) {
+ return ExcelToHtmlConverter.process(workbook);
}
}
*
* @param xlsStream workbook stream to process
* @return DOM representation of result HTML
- * @throws IOException
- * @throws ParserConfigurationException
+ * @throws IOException If an error occurs reading or writing files
+ * @throws ParserConfigurationException If configuration is incorrect
*/
- public static Document process( InputStream xlsStream ) throws IOException, ParserConfigurationException
- {
- final HSSFWorkbook workbook = new HSSFWorkbook( xlsStream );
- try {
- return ExcelToHtmlConverter.process( workbook );
- } finally {
- workbook.close();
+ public static Document process( InputStream xlsStream ) throws IOException, ParserConfigurationException {
+ try (HSSFWorkbook workbook = new HSSFWorkbook(xlsStream)) {
+ return ExcelToHtmlConverter.process(workbook);
}
}
*
* @param workbook workbook instance to process
* @return DOM representation of result HTML
- * @throws IOException
- * @throws ParserConfigurationException
+ * @throws IOException If an error occurs reading or writing files
+ * @throws ParserConfigurationException If configuration is incorrect
*/
- public static Document process( HSSFWorkbook workbook ) throws IOException, ParserConfigurationException
- {
+ public static Document process( HSSFWorkbook workbook ) throws IOException, ParserConfigurationException {
ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
XMLHelper.getDocumentBuilderFactory().newDocumentBuilder()
.newDocument() );
htmlDocumentFacade = new HtmlDocumentFacade( doc );
}
- public ExcelToHtmlConverter( HtmlDocumentFacade htmlDocumentFacade )
- {
+ public ExcelToHtmlConverter( HtmlDocumentFacade htmlDocumentFacade ) {
this.htmlDocumentFacade = htmlDocumentFacade;
}
- protected String buildStyle( HSSFWorkbook workbook, HSSFCellStyle cellStyle )
- {
+ protected String buildStyle( HSSFWorkbook workbook, HSSFCellStyle cellStyle ) {
StringBuilder style = new StringBuilder();
style.append( "white-space:pre-wrap;" );
final HSSFColor foregroundColor = cellStyle.getFillForegroundColorColor();
if ( foregroundColor == null ) break;
String fgCol = ExcelToHtmlUtils.getColor( foregroundColor );
- style.append( "background-color:" + fgCol + ";" );
+ style.append("background-color:").append(fgCol).append(";");
break;
default:
final HSSFColor backgroundColor = cellStyle.getFillBackgroundColorColor();
if ( backgroundColor == null ) break;
String bgCol = ExcelToHtmlUtils.getColor( backgroundColor );
- style.append( "background-color:" + bgCol + ";" );
+ style.append("background-color:").append(bgCol).append(";");
break;
}
}
private void buildStyle_border( HSSFWorkbook workbook, StringBuilder style,
- String type, BorderStyle xlsBorder, short borderColor )
- {
+ String type, BorderStyle xlsBorder, short borderColor ) {
if ( xlsBorder == BorderStyle.NONE ) {
return;
}
borderStyle.append( ExcelToHtmlUtils.getColor( color ) );
}
- style.append( "border-" + type + ":" + borderStyle + ";" );
+ style.append("border-").append(type).append(":").append(borderStyle).append(";");
}
void buildStyle_font( HSSFWorkbook workbook, StringBuilder style,
- HSSFFont font )
- {
+ HSSFFont font ) {
if ( font.getBold() )
{
style.append( "font-weight:bold;" );
final HSSFColor fontColor = workbook.getCustomPalette().getColor(
font.getColor() );
if ( fontColor != null )
- style.append( "color: " + ExcelToHtmlUtils.getColor( fontColor )
- + "; " );
+ style.append("color: ").append(ExcelToHtmlUtils.getColor(fontColor)).append("; ");
if ( font.getFontHeightInPoints() != 0 )
- style.append( "font-size:" + font.getFontHeightInPoints() + "pt;" );
+ style.append("font-size:").append(font.getFontHeightInPoints()).append("pt;");
if ( font.getItalic() )
{
}
protected String getStyleClassName( HSSFWorkbook workbook,
- HSSFCellStyle cellStyle )
- {
+ HSSFCellStyle cellStyle ) {
final Short cellStyleKey = Short.valueOf( cellStyle.getIndex() );
String knownClass = excelStyleToClass.get( cellStyleKey );
}
protected boolean processCell( HSSFCell cell, Element tableCellElement,
- int normalWidthPx, int maxSpannedWidthPx, float normalHeightPt )
- {
+ int normalWidthPx, int maxSpannedWidthPx, float normalHeightPt ) {
final HSSFCellStyle cellStyle = cell.getCellStyle();
String value;
- switch ( cell.getCellType() )
- {
+ switch ( cell.getCellType() ) {
case STRING:
// XXX: enrich
value = cell.getRichStringCellValue().getString();
break;
case FORMULA:
- switch ( cell.getCachedFormulaResultType() )
- {
+ switch ( cell.getCachedFormulaResultType() ) {
case STRING:
HSSFRichTextString str = cell.getRichStringCellValue();
if ( str != null && str.length() > 0 )
final boolean noText = ExcelToHtmlUtils.isEmpty( value );
final boolean wrapInDivs = !noText && isUseDivsToSpan() && !cellStyle.getWrapText();
- if ( cellStyle.getIndex() != 0 )
- {
+ if ( cellStyle.getIndex() != 0 ) {
@SuppressWarnings("resource")
HSSFWorkbook workbook = cell.getRow().getSheet().getWorkbook();
String mainCssClass = getStyleClassName( workbook, cellStyle );
}
}
- if ( isOutputLeadingSpacesAsNonBreaking() && value.startsWith( " " ) )
- {
+ if ( isOutputLeadingSpacesAsNonBreaking() && value.startsWith( " " ) ) {
StringBuilder builder = new StringBuilder();
for ( int c = 0; c < value.length(); c++ )
{
Text text = htmlDocumentFacade.createText( value );
- if ( wrapInDivs )
- {
+ if ( wrapInDivs ) {
Element outerDiv = htmlDocumentFacade.createBlock();
outerDiv.setAttribute( "class", this.cssClassContainerDiv );
innerDivStyle.append( "position:absolute;min-width:" );
innerDivStyle.append( normalWidthPx );
innerDivStyle.append( "px;" );
- if ( maxSpannedWidthPx != Integer.MAX_VALUE )
- {
+ if ( maxSpannedWidthPx != Integer.MAX_VALUE ) {
innerDivStyle.append( "max-width:" );
innerDivStyle.append( maxSpannedWidthPx );
innerDivStyle.append( "px;" );
innerDiv.appendChild( text );
outerDiv.appendChild( innerDiv );
tableCellElement.appendChild( outerDiv );
- }
- else
- {
+ } else {
tableCellElement.appendChild( text );
}
}
protected void processColumnHeaders( HSSFSheet sheet, int maxSheetColumns,
- Element table )
- {
+ Element table ) {
Element tableHeader = htmlDocumentFacade.createTableHeader();
table.appendChild( tableHeader );
Element tr = htmlDocumentFacade.createTableRow();
- if ( isOutputRowNumbers() )
- {
+ if ( isOutputRowNumbers() ) {
// empty row at left-top corner
tr.appendChild( htmlDocumentFacade.createTableHeaderCell() );
}
- for ( int c = 0; c < maxSheetColumns; c++ )
- {
+ for ( int c = 0; c < maxSheetColumns; c++ ) {
if ( !isOutputHiddenColumns() && sheet.isColumnHidden( c ) )
continue;
* first if <tt>{@link #isOutputRowNumbers()}==true</tt>)
*/
protected void processColumnWidths( HSSFSheet sheet, int maxSheetColumns,
- Element table )
- {
+ Element table ) {
// draw COLS after we know max column number
Element columnGroup = htmlDocumentFacade.createTableColumnGroup();
if ( isOutputRowNumbers() )
table.appendChild( columnGroup );
}
- protected void processDocumentInformation(
- SummaryInformation summaryInformation )
- {
+ protected void processDocumentInformation(SummaryInformation summaryInformation ) {
if ( ExcelToHtmlUtils.isNotEmpty( summaryInformation.getTitle() ) )
htmlDocumentFacade.setTitle( summaryInformation.getTitle() );
* @return maximum 1-base index of column that were rendered, zero if none
*/
protected int processRow( CellRangeAddress[][] mergedRanges, HSSFRow row,
- Element tableRowElement )
- {
+ Element tableRowElement ) {
final HSSFSheet sheet = row.getSheet();
final short maxColIx = row.getLastCellNum();
if ( maxColIx <= 0 )
emptyCell = processCell( cell, tableCellElement,
getColumnWidth( sheet, colIx ), divWidthPx,
row.getHeight() / 20f );
- }
- else
- {
+ } else {
emptyCell = true;
}
- if ( emptyCell )
- {
+ if ( emptyCell ) {
emptyCells.add( tableCellElement );
- }
- else
- {
+ } else {
for ( Element emptyCellElement : emptyCells )
{
tableRowElement.appendChild( emptyCellElement );
}
protected void processRowNumber( HSSFRow row,
- Element tableRowNumberCellElement )
- {
+ Element tableRowNumberCellElement ) {
tableRowNumberCellElement.setAttribute( "class", "rownumber" );
Text text = htmlDocumentFacade.createText( getRowName( row ) );
tableRowNumberCellElement.appendChild( text );
}
- protected void processSheet( HSSFSheet sheet )
- {
+ protected void processSheet( HSSFSheet sheet ) {
processSheetHeader( htmlDocumentFacade.getBody(), sheet );
final int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
final List<Element> emptyRowElements = new ArrayList<>(
physicalNumberOfRows);
int maxSheetColumns = 1;
- for ( int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++ )
- {
+ for ( int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++ ) {
HSSFRow row = sheet.getRow( r );
if ( row == null )
int maxRowColumnNumber = processRow( mergedRanges, row,
tableRowElement );
- if ( maxRowColumnNumber == 0 )
- {
+ if ( maxRowColumnNumber == 0 ) {
emptyRowElements.add( tableRowElement );
- }
- else
- {
- if ( !emptyRowElements.isEmpty() )
- {
- for ( Element emptyRowElement : emptyRowElements )
- {
+ } else {
+ if ( !emptyRowElements.isEmpty() ) {
+ for ( Element emptyRowElement : emptyRowElements ) {
tableBody.appendChild( emptyRowElement );
}
emptyRowElements.clear();
processColumnWidths( sheet, maxSheetColumns, table );
- if ( isOutputColumnHeaders() )
- {
+ if ( isOutputColumnHeaders() ) {
processColumnHeaders( sheet, maxSheetColumns, table );
}
htmlDocumentFacade.getBody().appendChild( table );
}
- protected void processSheetHeader( Element htmlBody, HSSFSheet sheet )
- {
+ protected void processSheetHeader( Element htmlBody, HSSFSheet sheet ) {
Element h2 = htmlDocumentFacade.createHeader2();
h2.appendChild( htmlDocumentFacade.createText( sheet.getSheetName() ) );
htmlBody.appendChild( h2 );
}
- public void processWorkbook( HSSFWorkbook workbook )
- {
+ public void processWorkbook( HSSFWorkbook workbook ) {
final SummaryInformation summaryInformation = workbook
.getSummaryInformation();
- if ( summaryInformation != null )
- {
+ if ( summaryInformation != null ) {
processDocumentInformation( summaryInformation );
}
- if ( isUseDivsToSpan() )
- {
+ if ( isUseDivsToSpan() ) {
// prepare CSS classes for later usage
this.cssClassContainerCell = htmlDocumentFacade
.getOrCreateCssClass( cssClassPrefixCell,
cssClassPrefixDiv, "position:relative;" );
}
- for ( int s = 0; s < workbook.getNumberOfSheets(); s++ )
- {
+ for ( int s = 0; s < workbook.getNumberOfSheets(); s++ ) {
HSSFSheet sheet = workbook.getSheetAt( s );
processSheet( sheet );
}
import java.util.Arrays;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
+import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.Beta;
@Beta
-public class ExcelToHtmlUtils extends AbstractExcelUtils
-{
- public static void appendAlign( StringBuilder style, HorizontalAlignment alignment )
- {
+public class ExcelToHtmlUtils extends AbstractExcelUtils {
+ public static void appendAlign( StringBuilder style, HorizontalAlignment alignment ) {
String cssAlign = getAlign( alignment );
if ( isEmpty( cssAlign ) )
return;
*
* @see #getMergedRange(CellRangeAddress[][], int, int)
*/
- public static CellRangeAddress[][] buildMergedRangesMap( HSSFSheet sheet )
- {
+ public static CellRangeAddress[][] buildMergedRangesMap( Sheet sheet ) {
CellRangeAddress[][] mergedRanges = new CellRangeAddress[1][];
- for ( final CellRangeAddress cellRangeAddress : sheet.getMergedRegions() )
- {
+ for ( final CellRangeAddress cellRangeAddress : sheet.getMergedRegions() ) {
final int requiredHeight = cellRangeAddress.getLastRow() + 1;
- if ( mergedRanges.length < requiredHeight )
- {
+ if ( mergedRanges.length < requiredHeight ) {
CellRangeAddress[][] newArray = new CellRangeAddress[requiredHeight][];
System.arraycopy( mergedRanges, 0, newArray, 0,
mergedRanges.length );
}
for ( int r = cellRangeAddress.getFirstRow(); r <= cellRangeAddress
- .getLastRow(); r++ )
- {
+ .getLastRow(); r++ ) {
final int requiredWidth = cellRangeAddress.getLastColumn() + 1;
CellRangeAddress[] rowMerged = mergedRanges[r];
- if ( rowMerged == null )
- {
+ if ( rowMerged == null ) {
rowMerged = new CellRangeAddress[requiredWidth];
mergedRanges[r] = rowMerged;
- }
- else
- {
+ } else {
final int rowMergedLength = rowMerged.length;
if ( rowMergedLength < requiredWidth )
{
}
return mergedRanges;
}
-
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assume.assumeTrue;
import java.util.Set;
import java.util.HashSet;
-import java.util.Iterator;
import org.apache.commons.collections4.IteratorUtils;
/**
assertCellRangesEqual(asArray(A1_B2), merge(A1, B1, A2, B2));
assertCellRangesEqual(asArray(A1_B2), merge(A1, B2, A2, B1));
- // Partially mergeable: multiple possible mergings
+ // Partially mergeable: multiple possible merges
// A B
// 1 x x A1,A2,B1 --> A1:B1,A2 or A1:A2,B1
// 2 x
}
return set;
}
-
- private static <T> T[] asArray(T...ts) {
+
+ private static CellRangeAddress[] asArray(CellRangeAddress...ts) {
return ts;
}