Fix IntelliJ warnings and code formatting, generalize ExcelToHtmlUtils, use try-with-resources, update/enhance JavaDoc somewhat

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1819402 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Dominik Stadler 2017-12-28 08:45:26 +00:00
parent 31ae97e748
commit 822188c49a
24 changed files with 168 additions and 360 deletions

View File

@ -405,13 +405,10 @@ public class TestAllFiles {
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);

View File

@ -99,16 +99,13 @@ public abstract class AbstractFileHandler implements FileHandler {
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())) {
@ -124,18 +121,12 @@ public abstract class AbstractFileHandler implements FileHandler {
}
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();
}
}

View File

@ -68,11 +68,8 @@ public class HDGFFileHandler extends POIFSFileHandler {
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();

View File

@ -51,11 +51,8 @@ public class HMEFFileHandler extends AbstractFileHandler {
@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();
}
}
}

View File

@ -56,11 +56,8 @@ public class HPBFFileHandler extends POIFSFileHandler {
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();

View File

@ -88,11 +88,8 @@ public class HPSFFileHandler extends POIFSFileHandler {
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);
}
}
@ -122,12 +119,9 @@ public class HPSFFileHandler extends POIFSFileHandler {
@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

View File

@ -58,12 +58,7 @@ public class HSLFFileHandler extends SlideShowHandler {
@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");
@ -82,11 +77,8 @@ public class HSLFFileHandler extends SlideShowHandler {
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);
@ -94,11 +86,8 @@ public class HSLFFileHandler extends SlideShowHandler {
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();
}
}
}

View File

@ -79,11 +79,8 @@ public class HSMFFileHandler extends POIFSFileHandler {
@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);

View File

@ -65,12 +65,9 @@ public class OPCFileHandler extends AbstractFileHandler {
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);
}

View File

@ -34,27 +34,21 @@ public class POIFSFileHandler extends AbstractFileHandler {
@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();
}
}
@ -78,11 +72,8 @@ public class POIFSFileHandler extends AbstractFileHandler {
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);

View File

@ -51,12 +51,9 @@ public abstract class SlideShowHandler extends POIFSFileHandler {
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();
}
}

View File

@ -36,12 +36,9 @@ public class XDGFFileHandler extends AbstractFileHandler {
// 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();
}
}
}

View File

@ -52,17 +52,14 @@ public class XSLFFileHandler extends SlideShowHandler {
// 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
@ -70,11 +67,8 @@ public class XSLFFileHandler extends SlideShowHandler {
@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);

View File

@ -39,11 +39,8 @@ public class XSSFBFileHandler extends AbstractFileHandler {
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)));
@ -86,11 +83,8 @@ public class XSSFBFileHandler extends AbstractFileHandler {
@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);
}

View File

@ -195,19 +195,7 @@ public class XSSFFileHandler extends SpreadsheetHandler {
} 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;
}
@ -221,11 +209,8 @@ public class XSSFFileHandler extends SpreadsheetHandler {
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);

View File

@ -40,11 +40,8 @@ public class XWPFFileHandler extends AbstractFileHandler {
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);

View File

@ -95,11 +95,13 @@ public final class IOUtils {
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);
@ -107,6 +109,12 @@ public final class IOUtils {
/**
* 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);

View File

@ -1448,7 +1448,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
*
* @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;

View File

@ -238,7 +238,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
* @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);
@ -289,8 +289,8 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
* @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);

View File

@ -104,7 +104,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
this.run = r;
this.parent = p;
/**
/*
* reserve already occupied drawing ids, so reserving new ids later will
* not corrupt the document
*/
@ -256,10 +256,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/
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());
}
/**
@ -366,9 +363,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/
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());
}
/**
@ -445,9 +440,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/
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());
}
/**
@ -498,9 +491,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/
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());
}
/**
@ -517,9 +508,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
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) {
@ -530,9 +519,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
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) {
@ -543,9 +530,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
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) {
@ -556,9 +541,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
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) {
@ -569,9 +552,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
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) {
@ -607,7 +588,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* the contents of this run.
* </p>
*
* @param valign
* @param valign Type of vertical align to apply
* @see VerticalAlign
*/
public void setSubscript(VerticalAlign valign) {
@ -671,7 +652,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* <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) {
@ -716,7 +697,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* 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) {
@ -773,7 +754,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* 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);
@ -816,7 +797,8 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* 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);
@ -923,8 +905,8 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* @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
@ -1027,9 +1009,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
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);
}
}

View File

@ -20,15 +20,14 @@ import java.io.File;
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}
@ -38,16 +37,13 @@ import org.apache.poi.util.IOUtils;
* @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:
@ -68,11 +64,9 @@ public class AbstractExcelUtils
}
}
public static String getBorderStyle( BorderStyle xlsBorder )
{
public static String getBorderStyle( BorderStyle xlsBorder ) {
final String borderStyle;
switch ( xlsBorder )
{
switch ( xlsBorder ) {
case NONE:
borderStyle = "none";
break;
@ -99,11 +93,9 @@ public class AbstractExcelUtils
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:
@ -119,12 +111,10 @@ public class AbstractExcelUtils
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' );
@ -152,8 +142,7 @@ public class AbstractExcelUtils
* "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;
@ -167,13 +156,12 @@ public class AbstractExcelUtils
/**
* @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;
@ -192,17 +180,9 @@ public class AbstractExcelUtils
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 );
}
}
}

View File

@ -27,7 +27,6 @@ import java.util.Map;
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;
@ -59,9 +58,7 @@ import org.w3c.dom.Text;
* @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 );
@ -73,16 +70,10 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* </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;
}
@ -109,16 +100,12 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* @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);
}
}
@ -127,16 +114,12 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
*
* @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);
}
}
@ -145,11 +128,10 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
*
* @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() );
@ -180,13 +162,11 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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;" );
@ -199,13 +179,13 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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;
}
@ -225,8 +205,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
}
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;
}
@ -244,12 +223,11 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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;" );
@ -258,11 +236,10 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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() )
{
@ -296,8 +273,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
}
protected String getStyleClassName( HSSFWorkbook workbook,
HSSFCellStyle cellStyle )
{
HSSFCellStyle cellStyle ) {
final Short cellStyleKey = Short.valueOf( cellStyle.getIndex() );
String knownClass = excelStyleToClass.get( cellStyleKey );
@ -317,20 +293,17 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
}
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 )
@ -384,8 +357,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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 );
@ -407,8 +379,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
}
}
if ( isOutputLeadingSpacesAsNonBreaking() && value.startsWith( " " ) )
{
if ( isOutputLeadingSpacesAsNonBreaking() && value.startsWith( " " ) ) {
StringBuilder builder = new StringBuilder();
for ( int c = 0; c < value.length(); c++ )
{
@ -425,8 +396,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
Text text = htmlDocumentFacade.createText( value );
if ( wrapInDivs )
{
if ( wrapInDivs ) {
Element outerDiv = htmlDocumentFacade.createBlock();
outerDiv.setAttribute( "class", this.cssClassContainerDiv );
@ -435,8 +405,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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;" );
@ -451,9 +420,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
innerDiv.appendChild( text );
outerDiv.appendChild( innerDiv );
tableCellElement.appendChild( outerDiv );
}
else
{
} else {
tableCellElement.appendChild( text );
}
@ -461,21 +428,18 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
}
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;
@ -492,8 +456,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* 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() )
@ -513,9 +476,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
table.appendChild( columnGroup );
}
protected void processDocumentInformation(
SummaryInformation summaryInformation )
{
protected void processDocumentInformation(SummaryInformation summaryInformation ) {
if ( ExcelToHtmlUtils.isNotEmpty( summaryInformation.getTitle() ) )
htmlDocumentFacade.setTitle( summaryInformation.getTitle() );
@ -534,8 +495,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* @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 )
@ -615,18 +575,13 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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 );
@ -642,15 +597,13 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
}
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();
@ -669,8 +622,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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 )
@ -687,16 +639,11 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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();
@ -709,8 +656,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
processColumnWidths( sheet, maxSheetColumns, table );
if ( isOutputColumnHeaders() )
{
if ( isOutputColumnHeaders() ) {
processColumnHeaders( sheet, maxSheetColumns, table );
}
@ -719,24 +665,20 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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,
@ -745,8 +687,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
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 );
}

View File

@ -18,16 +18,14 @@ package org.apache.poi.hssf.converter;
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;
@ -44,14 +42,11 @@ public class ExcelToHtmlUtils extends AbstractExcelUtils
*
* @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 );
@ -59,18 +54,14 @@ public class ExcelToHtmlUtils extends AbstractExcelUtils
}
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 )
{
@ -89,5 +80,4 @@ public class ExcelToHtmlUtils extends AbstractExcelUtils
}
return mergedRanges;
}
}

View File

@ -20,10 +20,8 @@ package org.apache.poi.ss.util;
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;
/**
@ -54,7 +52,7 @@ public final class TestCellRangeUtil {
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
@ -82,8 +80,8 @@ public final class TestCellRangeUtil {
}
return set;
}
private static <T> T[] asArray(T...ts) {
private static CellRangeAddress[] asArray(CellRangeAddress...ts) {
return ts;
}