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); boolean ignoreHPSF = (handler instanceof HPSFFileHandler);
try { try {
InputStream stream = new BufferedInputStream(new FileInputStream(inputFile), 64*1024); try (InputStream stream = new BufferedInputStream(new FileInputStream(inputFile), 64 * 1024)) {
try {
handler.handleFile(stream, file); handler.handleFile(stream, file);
assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!", assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!",
OLD_FILES_HWPF.contains(file) && !ignoreHPSF); OLD_FILES_HWPF.contains(file) && !ignoreHPSF);
} finally {
stream.close();
} }
handler.handleExtracting(inputFile); handler.handleExtracting(inputFile);

View File

@ -99,15 +99,12 @@ public abstract class AbstractFileHandler implements FileHandler {
handleExtractingAsStream(file); handleExtractingAsStream(file);
if(extractor instanceof POIOLE2TextExtractor) { if(extractor instanceof POIOLE2TextExtractor) {
HPSFPropertiesExtractor hpsfExtractor = new HPSFPropertiesExtractor((POIOLE2TextExtractor)extractor); try (HPSFPropertiesExtractor hpsfExtractor = new HPSFPropertiesExtractor((POIOLE2TextExtractor) extractor)) {
try {
assertNotNull(hpsfExtractor.getDocumentSummaryInformationText()); assertNotNull(hpsfExtractor.getDocumentSummaryInformationText());
assertNotNull(hpsfExtractor.getSummaryInformationText()); assertNotNull(hpsfExtractor.getSummaryInformationText());
String text = hpsfExtractor.getText(); String text = hpsfExtractor.getText();
//System.out.println(text); //System.out.println(text);
assertNotNull(text); assertNotNull(text);
} finally {
hpsfExtractor.close();
} }
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -124,18 +121,12 @@ public abstract class AbstractFileHandler implements FileHandler {
} }
private void handleExtractingAsStream(File file) throws IOException, OpenXML4JException, XmlException { private void handleExtractingAsStream(File file) throws IOException, OpenXML4JException, XmlException {
InputStream stream = new FileInputStream(file); try (InputStream stream = new FileInputStream(file)) {
try { try (POITextExtractor streamExtractor = ExtractorFactory.createExtractor(stream)) {
POITextExtractor streamExtractor = ExtractorFactory.createExtractor(stream);
try {
assertNotNull(streamExtractor); assertNotNull(streamExtractor);
assertNotNull(streamExtractor.getText()); assertNotNull(streamExtractor.getText());
} finally {
streamExtractor.close();
} }
} finally {
stream.close();
} }
} }

View File

@ -68,11 +68,8 @@ public class HDGFFileHandler extends POIFSFileHandler {
stream = new FileInputStream(file); stream = new FileInputStream(file);
try { try {
VisioTextExtractor extractor = new VisioTextExtractor(stream); try (VisioTextExtractor extractor = new VisioTextExtractor(stream)) {
try {
assertNotNull(extractor.getText()); assertNotNull(extractor.getText());
} finally {
extractor.close();
} }
} finally { } finally {
stream.close(); stream.close();

View File

@ -51,11 +51,8 @@ public class HMEFFileHandler extends AbstractFileHandler {
@Test @Test
public void test() throws Exception { public void test() throws Exception {
String path = "test-data/hmef/quick-winmail.dat"; String path = "test-data/hmef/quick-winmail.dat";
InputStream stream = new FileInputStream(path); try (InputStream stream = new FileInputStream(path)) {
try {
handleFile(stream, path); handleFile(stream, path);
} finally {
stream.close();
} }
} }
} }

View File

@ -56,11 +56,8 @@ public class HPBFFileHandler extends POIFSFileHandler {
stream = new FileInputStream(file); stream = new FileInputStream(file);
try { try {
PublisherTextExtractor extractor = new PublisherTextExtractor(stream); try (PublisherTextExtractor extractor = new PublisherTextExtractor(stream)) {
try {
assertNotNull(extractor.getText()); assertNotNull(extractor.getText());
} finally {
extractor.close();
} }
} finally { } finally {
stream.close(); stream.close();

View File

@ -88,11 +88,8 @@ public class HPSFFileHandler extends POIFSFileHandler {
if (!root.hasEntry(streamName)) { if (!root.hasEntry(streamName)) {
return false; return false;
} }
DocumentInputStream dis = root.createDocumentInputStream(streamName); try (DocumentInputStream dis = root.createDocumentInputStream(streamName)) {
try {
return PropertySet.isPropertySetStream(dis); return PropertySet.isPropertySetStream(dis);
} finally {
dis.close();
} }
} }
@ -122,11 +119,8 @@ public class HPSFFileHandler extends POIFSFileHandler {
@Test @Test
public void test() throws Exception { public void test() throws Exception {
String path = "test-data/hpsf/Test0313rur.adm"; String path = "test-data/hpsf/Test0313rur.adm";
InputStream stream = new FileInputStream(path); try (InputStream stream = new FileInputStream(path)) {
try {
handleFile(stream, path); handleFile(stream, path);
} finally {
stream.close();
} }
} }

View File

@ -58,12 +58,7 @@ public class HSLFFileHandler extends SlideShowHandler {
@Override @Override
@Test @Test
public void test() throws Exception { public void test() throws Exception {
File[] files = new File("test-data/slideshow/").listFiles(new FilenameFilter() { File[] files = new File("test-data/slideshow/").listFiles((dir, name) -> name.endsWith(".ppt"));
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".ppt");
}
});
assertNotNull(files); assertNotNull(files);
System.out.println("Testing " + files.length + " files"); System.out.println("Testing " + files.length + " files");
@ -82,11 +77,8 @@ public class HSLFFileHandler extends SlideShowHandler {
System.out.println(file); System.out.println(file);
//System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger"); //System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger");
InputStream stream = new FileInputStream(file); try (InputStream stream = new FileInputStream(file)) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
handleExtracting(file); handleExtracting(file);
@ -94,11 +86,8 @@ public class HSLFFileHandler extends SlideShowHandler {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger"); System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger");
InputStream stream = new FileInputStream(args[0]); try (InputStream stream = new FileInputStream(args[0])) {
try {
new HSLFFileHandler().handleFile(stream, args[0]); new HSLFFileHandler().handleFile(stream, args[0]);
} finally {
stream.close();
} }
} }
} }

View File

@ -79,11 +79,8 @@ public class HSMFFileHandler extends POIFSFileHandler {
@Test @Test
public void test() throws Exception { public void test() throws Exception {
File file = new File("test-data/hsmf/logsat.com_signatures_valid.msg"); File file = new File("test-data/hsmf/logsat.com_signatures_valid.msg");
InputStream stream = new FileInputStream(file); try (InputStream stream = new FileInputStream(file)) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
handleExtracting(file); handleExtracting(file);

View File

@ -65,11 +65,8 @@ public class OPCFileHandler extends AbstractFileHandler {
public void test() throws Exception { public void test() throws Exception {
File file = new File("test-data/diagram/test.vsdx"); File file = new File("test-data/diagram/test.vsdx");
InputStream stream = new PushbackInputStream(new FileInputStream(file), 100000); try (InputStream stream = new PushbackInputStream(new FileInputStream(file), 100000)) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
handleExtracting(file); handleExtracting(file);

View File

@ -34,18 +34,14 @@ public class POIFSFileHandler extends AbstractFileHandler {
@Override @Override
public void handleFile(InputStream stream, String path) throws Exception { public void handleFile(InputStream stream, String path) throws Exception {
POIFSFileSystem fs = new POIFSFileSystem(stream); try (POIFSFileSystem fs = new POIFSFileSystem(stream)) {
try {
handlePOIFSFileSystem(fs); handlePOIFSFileSystem(fs);
handleHPSFProperties(fs); handleHPSFProperties(fs);
} finally {
fs.close();
} }
} }
private void handleHPSFProperties(POIFSFileSystem fs) throws IOException { private void handleHPSFProperties(POIFSFileSystem fs) throws IOException {
HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs); try (HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) {
try {
// can be null // can be null
ext.getDocSummaryInformation(); ext.getDocSummaryInformation();
ext.getSummaryInformation(); ext.getSummaryInformation();
@ -53,8 +49,6 @@ public class POIFSFileHandler extends AbstractFileHandler {
assertNotNull(ext.getDocumentSummaryInformationText()); assertNotNull(ext.getDocumentSummaryInformationText());
assertNotNull(ext.getSummaryInformationText()); assertNotNull(ext.getSummaryInformationText());
assertNotNull(ext.getText()); assertNotNull(ext.getText());
} finally {
ext.close();
} }
} }
@ -78,11 +72,8 @@ public class POIFSFileHandler extends AbstractFileHandler {
public void test() throws Exception { public void test() throws Exception {
File file = new File("test-data/poifs/Notes.ole2"); File file = new File("test-data/poifs/Notes.ole2");
InputStream stream = new FileInputStream(file); try (InputStream stream = new FileInputStream(file)) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
//handleExtracting(file); //handleExtracting(file);

View File

@ -51,12 +51,9 @@ public abstract class SlideShowHandler extends POIFSFileHandler {
readContent(ss); readContent(ss);
// read in the written file // read in the written file
SlideShow<?,?> read = SlideShowFactory.create(new ByteArrayInputStream(out.toByteArray())); try (SlideShow<?, ?> read = SlideShowFactory.create(new ByteArrayInputStream(out.toByteArray()))) {
try {
assertNotNull(read); assertNotNull(read);
readContent(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 // a test-case to test this locally without executing the full TestAllFiles
@Test @Test
public void test() throws Exception { public void test() throws Exception {
OPCPackage pkg = OPCPackage.open("test-data/diagram/test.vsdx", PackageAccess.READ); try (OPCPackage pkg = OPCPackage.open("test-data/diagram/test.vsdx", PackageAccess.READ)) {
try {
XmlVisioDocument doc = new XmlVisioDocument(pkg); XmlVisioDocument doc = new XmlVisioDocument(pkg);
new POIXMLDocumentHandler().handlePOIXMLDocument(doc); new POIXMLDocumentHandler().handlePOIXMLDocument(doc);
} finally {
pkg.close();
} }
} }
} }

View File

@ -53,15 +53,12 @@ public class XSLFFileHandler extends SlideShowHandler {
// additionally try the other getText() methods // additionally try the other getText() methods
XSLFPowerPointExtractor extractor = (XSLFPowerPointExtractor) ExtractorFactory.createExtractor(file); try (XSLFPowerPointExtractor extractor = (XSLFPowerPointExtractor) ExtractorFactory.createExtractor(file)) {
try {
assertNotNull(extractor); assertNotNull(extractor);
assertNotNull(extractor.getText(true, true, true)); assertNotNull(extractor.getText(true, true, true));
assertEquals("With all options disabled we should not get text", assertEquals("With all options disabled we should not get text",
"", extractor.getText(false, false, false)); "", extractor.getText(false, false, false));
} finally {
extractor.close();
} }
} }
@ -70,11 +67,8 @@ public class XSLFFileHandler extends SlideShowHandler {
@Test @Test
public void test() throws Exception { public void test() throws Exception {
File file = new File("test-data/slideshow/ae.ac.uaeu.faculty_nafaachbili_GeomLec1.pptx"); File file = new File("test-data/slideshow/ae.ac.uaeu.faculty_nafaachbili_GeomLec1.pptx");
InputStream stream = new FileInputStream(file); try (InputStream stream = new FileInputStream(file)) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
handleExtracting(file); handleExtracting(file);

View File

@ -39,11 +39,8 @@ public class XSSFBFileHandler extends AbstractFileHandler {
IOUtils.copy(stream, out); IOUtils.copy(stream, out);
final byte[] bytes = out.toByteArray(); final byte[] bytes = out.toByteArray();
OPCPackage opcPackage = OPCPackage.open(new ByteArrayInputStream(bytes)); try (OPCPackage opcPackage = OPCPackage.open(new ByteArrayInputStream(bytes))) {
try {
testOne(opcPackage); testOne(opcPackage);
} finally {
opcPackage.close();
} }
testNotHandledByWorkbookException(OPCPackage.open(new ByteArrayInputStream(bytes))); testNotHandledByWorkbookException(OPCPackage.open(new ByteArrayInputStream(bytes)));
@ -86,11 +83,8 @@ public class XSSFBFileHandler extends AbstractFileHandler {
@Test @Test
public void testLocal() throws Exception { public void testLocal() throws Exception {
File file = new File("test-data/spreadsheet/Simple.xlsb"); File file = new File("test-data/spreadsheet/Simple.xlsb");
FileInputStream stream = new FileInputStream(file); try (FileInputStream stream = new FileInputStream(file)) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
handleExtracting(file); handleExtracting(file);
} }

View File

@ -195,19 +195,7 @@ public class XSSFFileHandler extends SpreadsheetHandler {
} catch (OLE2NotOfficeXmlFileException e) { } catch (OLE2NotOfficeXmlFileException e) {
// we have some files that are not actually OOXML and thus cannot be tested here // we have some files that are not actually OOXML and thus cannot be tested here
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException | InvalidFormatException | POIXMLException | IOException 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) {
if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
throw e; throw e;
} }
@ -221,11 +209,8 @@ public class XSSFFileHandler extends SpreadsheetHandler {
public void test() throws Exception { public void test() throws Exception {
File file = new File("test-data/spreadsheet/ref-56737.xlsx"); File file = new File("test-data/spreadsheet/ref-56737.xlsx");
InputStream stream = new BufferedInputStream(new FileInputStream(file)); try (InputStream stream = new BufferedInputStream(new FileInputStream(file))) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
handleExtracting(file); handleExtracting(file);

View File

@ -40,11 +40,8 @@ public class XWPFFileHandler extends AbstractFileHandler {
public void test() throws Exception { public void test() throws Exception {
File file = new File("test-data/document/51921-Word-Crash067.docx"); File file = new File("test-data/document/51921-Word-Crash067.docx");
InputStream stream = new BufferedInputStream(new FileInputStream(file)); try (InputStream stream = new BufferedInputStream(new FileInputStream(file))) {
try {
handleFile(stream, file.getPath()); handleFile(stream, file.getPath());
} finally {
stream.close();
} }
handleExtracting(file); handleExtracting(file);

View File

@ -96,10 +96,12 @@ public final class IOUtils {
return peekedBytes; return peekedBytes;
} }
/** /**
* Reads all the data from the input stream, and returns the bytes read. * 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 { public static byte[] toByteArray(InputStream stream) throws IOException {
return toByteArray(stream, Integer.MAX_VALUE); 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. * 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 { public static byte[] toByteArray(InputStream stream, int length) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Integer.MAX_VALUE ? 4096 : length); 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 * @param format
* @return the next free ImageNumber * @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 { public int getNextPicNameNumber(int format) throws InvalidFormatException {
int img = getAllPackagePictures().size() + 1; 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 pictureData The picture data
* @param format The format of the picture. * @param format The format of the picture.
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . * @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 { public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException {
XWPFPictureData xwpfPicData = document.findPackagePictureData(pictureData, format); 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 is The stream to read image from
* @param format The format of the picture. * @param format The format of the picture.
* @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . * @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.
* @throws IOException * @throws IOException If reading the picture-data from the stream fails.
*/ */
public String addPictureData(InputStream is, int format) throws InvalidFormatException, IOException { public String addPictureData(InputStream is, int format) throws InvalidFormatException, IOException {
byte[] data = IOUtils.toByteArray(is); byte[] data = IOUtils.toByteArray(is);

View File

@ -104,7 +104,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
this.run = r; this.run = r;
this.parent = p; this.parent = p;
/** /*
* reserve already occupied drawing ids, so reserving new ids later will * reserve already occupied drawing ids, so reserving new ids later will
* not corrupt the document * not corrupt the document
*/ */
@ -256,10 +256,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/ */
public boolean isBold() { public boolean isBold() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetB()) { return pr != null && pr.isSetB() && isCTOnOff(pr.getB());
return false;
}
return isCTOnOff(pr.getB());
} }
/** /**
@ -366,9 +363,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/ */
public boolean isItalic() { public boolean isItalic() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetI()) return pr != null && pr.isSetI() && isCTOnOff(pr.getI());
return false;
return isCTOnOff(pr.getI());
} }
/** /**
@ -445,9 +440,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/ */
public boolean isStrikeThrough() { public boolean isStrikeThrough() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetStrike()) return pr != null && pr.isSetStrike() && isCTOnOff(pr.getStrike());
return false;
return isCTOnOff(pr.getStrike());
} }
/** /**
@ -498,9 +491,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
*/ */
public boolean isDoubleStrikeThrough() { public boolean isDoubleStrikeThrough() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetDstrike()) return pr != null && pr.isSetDstrike() && isCTOnOff(pr.getDstrike());
return false;
return isCTOnOff(pr.getDstrike());
} }
/** /**
@ -517,9 +508,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isSmallCaps() { public boolean isSmallCaps() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetSmallCaps()) return pr != null && pr.isSetSmallCaps() && isCTOnOff(pr.getSmallCaps());
return false;
return isCTOnOff(pr.getSmallCaps());
} }
public void setSmallCaps(boolean value) { public void setSmallCaps(boolean value) {
@ -530,9 +519,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isCapitalized() { public boolean isCapitalized() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetCaps()) return pr != null && pr.isSetCaps() && isCTOnOff(pr.getCaps());
return false;
return isCTOnOff(pr.getCaps());
} }
public void setCapitalized(boolean value) { public void setCapitalized(boolean value) {
@ -543,9 +530,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isShadowed() { public boolean isShadowed() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetShadow()) return pr != null && pr.isSetShadow() && isCTOnOff(pr.getShadow());
return false;
return isCTOnOff(pr.getShadow());
} }
public void setShadow(boolean value) { public void setShadow(boolean value) {
@ -556,9 +541,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isImprinted() { public boolean isImprinted() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetImprint()) return pr != null && pr.isSetImprint() && isCTOnOff(pr.getImprint());
return false;
return isCTOnOff(pr.getImprint());
} }
public void setImprinted(boolean value) { public void setImprinted(boolean value) {
@ -569,9 +552,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
public boolean isEmbossed() { public boolean isEmbossed() {
CTRPr pr = run.getRPr(); CTRPr pr = run.getRPr();
if (pr == null || !pr.isSetEmboss()) return pr != null && pr.isSetEmboss() && isCTOnOff(pr.getEmboss());
return false;
return isCTOnOff(pr.getEmboss());
} }
public void setEmbossed(boolean value) { public void setEmbossed(boolean value) {
@ -607,7 +588,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* the contents of this run. * the contents of this run.
* </p> * </p>
* *
* @param valign * @param valign Type of vertical align to apply
* @see VerticalAlign * @see VerticalAlign
*/ */
public void setSubscript(VerticalAlign valign) { public void setSubscript(VerticalAlign valign) {
@ -671,7 +652,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* <p> * <p>
* Also sets the other font ranges, if they haven't been set before * Also sets the other font ranges, if they haven't been set before
* *
* @param fontFamily * @param fontFamily The font family to apply
* @see FontCharRange * @see FontCharRange
*/ */
public void setFontFamily(String fontFamily) { 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 * ascii font char range with the given font family and also set all not
* specified font ranges * specified font ranges
* *
* @param fontFamily * @param fontFamily The font family to apply
* @param fcr FontCharRange or null for default handling * @param fcr FontCharRange or null for default handling
*/ */
public void setFontFamily(String fontFamily, FontCharRange fcr) { 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. * be used for non complex script characters.
* </p> * </p>
* *
* @param size * @param size The font size as number of point measurements.
*/ */
public void setFontSize(int size) { public void setFontSize(int size) {
BigInteger bint = new BigInteger("" + size); BigInteger bint = new BigInteger("" + size);
@ -816,7 +797,8 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* contents of this run. * contents of this run.
* </p> * </p>
* *
* @param val * @param val Positive values will raise the baseline of the text, negative
* values will lower it.
*/ */
public void setTextPosition(int val) { public void setTextPosition(int val) {
BigInteger bint = new BigInteger("" + 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 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 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} * @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 InvalidFormatException If the format of the picture is not known.
* @throws IOException * @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_EMF
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF
* @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT * @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); XWPFPicture xwpfPicture = new XWPFPicture(pic, this);
pictures.add(xwpfPicture); pictures.add(xwpfPicture);
return xwpfPicture; return xwpfPicture;
} catch (XmlException e) { } catch (XmlException | SAXException e) {
throw new IllegalStateException(e);
} catch (SAXException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
} }

View File

@ -20,15 +20,14 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hwpf.converter.AbstractWordUtils; import org.apache.poi.hwpf.converter.AbstractWordUtils;
import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment; 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.ss.util.CellRangeAddress;
import org.apache.poi.util.Beta; import org.apache.poi.util.Beta;
import org.apache.poi.util.IOUtils;
/** /**
* Common class for {@link ExcelToFoUtils} and {@link ExcelToHtmlUtils} * Common class for {@link ExcelToFoUtils} and {@link ExcelToHtmlUtils}
@ -38,16 +37,13 @@ import org.apache.poi.util.IOUtils;
* @since POI 3.8 beta 5 * @since POI 3.8 beta 5
*/ */
@Beta @Beta
public class AbstractExcelUtils public class AbstractExcelUtils {
{
/*package*/ static final String EMPTY = ""; /*package*/ static final String EMPTY = "";
private static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; private static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
private static final int UNIT_OFFSET_LENGTH = 7; private static final int UNIT_OFFSET_LENGTH = 7;
public static String getAlign( HorizontalAlignment alignment ) public static String getAlign( HorizontalAlignment alignment ) {
{ switch ( alignment ) {
switch ( alignment )
{
case CENTER: case CENTER:
return "center"; return "center";
case CENTER_SELECTION: 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; final String borderStyle;
switch ( xlsBorder ) switch ( xlsBorder ) {
{
case NONE: case NONE:
borderStyle = "none"; borderStyle = "none";
break; break;
@ -99,11 +93,9 @@ public class AbstractExcelUtils
return borderStyle; return borderStyle;
} }
public static String getBorderWidth( BorderStyle xlsBorder ) public static String getBorderWidth( BorderStyle xlsBorder ) {
{
final String borderWidth; final String borderWidth;
switch ( xlsBorder ) switch ( xlsBorder ) {
{
case MEDIUM_DASH_DOT: case MEDIUM_DASH_DOT:
case MEDIUM_DASH_DOT_DOT: case MEDIUM_DASH_DOT_DOT:
case MEDIUM_DASHED: case MEDIUM_DASHED:
@ -119,12 +111,10 @@ public class AbstractExcelUtils
return borderWidth; return borderWidth;
} }
public static String getColor( HSSFColor color ) public static String getColor( HSSFColor color ) {
{
StringBuilder stringBuilder = new StringBuilder( 7 ); StringBuilder stringBuilder = new StringBuilder( 7 );
stringBuilder.append( '#' ); stringBuilder.append( '#' );
for ( short s : color.getTriplet() ) for ( short s : color.getTriplet() ) {
{
if ( s < 10 ) if ( s < 10 )
stringBuilder.append( '0' ); 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" * "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 * >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 ) int pixels = ( widthUnits / EXCEL_COLUMN_WIDTH_FACTOR )
* UNIT_OFFSET_LENGTH; * UNIT_OFFSET_LENGTH;
@ -167,13 +156,12 @@ public class AbstractExcelUtils
/** /**
* @param mergedRanges * @param mergedRanges
* map of sheet merged ranges built with * 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 * @return {@link CellRangeAddress} from map if cell with specified row and
* column numbers contained in found range, <tt>null</tt> otherwise * column numbers contained in found range, <tt>null</tt> otherwise
*/ */
public static CellRangeAddress getMergedRange( public static CellRangeAddress getMergedRange(
CellRangeAddress[][] mergedRanges, int rowNumber, int columnNumber ) CellRangeAddress[][] mergedRanges, int rowNumber, int columnNumber ) {
{
CellRangeAddress[] mergedRangeRowInfo = rowNumber < mergedRanges.length ? mergedRanges[rowNumber] CellRangeAddress[] mergedRangeRowInfo = rowNumber < mergedRanges.length ? mergedRanges[rowNumber]
: null; : null;
@ -192,17 +180,9 @@ public class AbstractExcelUtils
return !isEmpty( str ); return !isEmpty( str );
} }
public static HSSFWorkbook loadXls( File xlsFile ) throws IOException public static HSSFWorkbook loadXls(File xlsFile ) throws IOException {
{ try (final FileInputStream inputStream = new FileInputStream( xlsFile )) {
final FileInputStream inputStream = new FileInputStream( xlsFile );
try
{
return new HSSFWorkbook( inputStream ); 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.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys; import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource; import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;
@ -59,9 +58,7 @@ import org.w3c.dom.Text;
* @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/ */
@Beta @Beta
public class ExcelToHtmlConverter extends AbstractExcelConverter public class ExcelToHtmlConverter extends AbstractExcelConverter {
{
private static final POILogger logger = POILogFactory private static final POILogger logger = POILogFactory
.getLogger( ExcelToHtmlConverter.class ); .getLogger( ExcelToHtmlConverter.class );
@ -73,16 +70,10 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* </p> * </p>
* Where infile is an input .xls file ( Word 97-2007) which will be rendered * Where infile is an input .xls file ( Word 97-2007) which will be rendered
* as HTML into outfile * as HTML into outfile
* @throws TransformerException
* @throws Exception
*/ */
public static void main( String[] args ) public static void main( String[] args ) throws Exception {
throws IOException, ParserConfigurationException, TransformerException if ( args.length < 2 ) {
{ System.err.println( "Usage: ExcelToHtmlConverter <inputFile.xls> <saveTo.html>" );
if ( args.length < 2 )
{
System.err
.println( "Usage: ExcelToHtmlConverter <inputFile.xls> <saveTo.html>" );
return; return;
} }
@ -109,16 +100,12 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* @param xlsFile * @param xlsFile
* workbook file to process * workbook file to process
* @return DOM representation of result HTML * @return DOM representation of result HTML
* @throws IOException * @throws IOException If an error occurs reading or writing files
* @throws ParserConfigurationException * @throws ParserConfigurationException If configuration is incorrect
*/ */
public static Document process( File xlsFile ) throws IOException, ParserConfigurationException public static Document process( File xlsFile ) throws IOException, ParserConfigurationException {
{ try (HSSFWorkbook workbook = ExcelToHtmlUtils.loadXls(xlsFile)) {
final HSSFWorkbook workbook = ExcelToHtmlUtils.loadXls( xlsFile );
try {
return ExcelToHtmlConverter.process(workbook); return ExcelToHtmlConverter.process(workbook);
} finally {
workbook.close();
} }
} }
@ -127,16 +114,12 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* *
* @param xlsStream workbook stream to process * @param xlsStream workbook stream to process
* @return DOM representation of result HTML * @return DOM representation of result HTML
* @throws IOException * @throws IOException If an error occurs reading or writing files
* @throws ParserConfigurationException * @throws ParserConfigurationException If configuration is incorrect
*/ */
public static Document process( InputStream xlsStream ) throws IOException, ParserConfigurationException public static Document process( InputStream xlsStream ) throws IOException, ParserConfigurationException {
{ try (HSSFWorkbook workbook = new HSSFWorkbook(xlsStream)) {
final HSSFWorkbook workbook = new HSSFWorkbook( xlsStream );
try {
return ExcelToHtmlConverter.process(workbook); return ExcelToHtmlConverter.process(workbook);
} finally {
workbook.close();
} }
} }
@ -145,11 +128,10 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* *
* @param workbook workbook instance to process * @param workbook workbook instance to process
* @return DOM representation of result HTML * @return DOM representation of result HTML
* @throws IOException * @throws IOException If an error occurs reading or writing files
* @throws ParserConfigurationException * @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( ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
XMLHelper.getDocumentBuilderFactory().newDocumentBuilder() XMLHelper.getDocumentBuilderFactory().newDocumentBuilder()
.newDocument() ); .newDocument() );
@ -180,13 +162,11 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
htmlDocumentFacade = new HtmlDocumentFacade( doc ); htmlDocumentFacade = new HtmlDocumentFacade( doc );
} }
public ExcelToHtmlConverter( HtmlDocumentFacade htmlDocumentFacade ) public ExcelToHtmlConverter( HtmlDocumentFacade htmlDocumentFacade ) {
{
this.htmlDocumentFacade = htmlDocumentFacade; this.htmlDocumentFacade = htmlDocumentFacade;
} }
protected String buildStyle( HSSFWorkbook workbook, HSSFCellStyle cellStyle ) protected String buildStyle( HSSFWorkbook workbook, HSSFCellStyle cellStyle ) {
{
StringBuilder style = new StringBuilder(); StringBuilder style = new StringBuilder();
style.append( "white-space:pre-wrap;" ); style.append( "white-space:pre-wrap;" );
@ -199,13 +179,13 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
final HSSFColor foregroundColor = cellStyle.getFillForegroundColorColor(); final HSSFColor foregroundColor = cellStyle.getFillForegroundColorColor();
if ( foregroundColor == null ) break; if ( foregroundColor == null ) break;
String fgCol = ExcelToHtmlUtils.getColor( foregroundColor ); String fgCol = ExcelToHtmlUtils.getColor( foregroundColor );
style.append( "background-color:" + fgCol + ";" ); style.append("background-color:").append(fgCol).append(";");
break; break;
default: default:
final HSSFColor backgroundColor = cellStyle.getFillBackgroundColorColor(); final HSSFColor backgroundColor = cellStyle.getFillBackgroundColorColor();
if ( backgroundColor == null ) break; if ( backgroundColor == null ) break;
String bgCol = ExcelToHtmlUtils.getColor( backgroundColor ); String bgCol = ExcelToHtmlUtils.getColor( backgroundColor );
style.append( "background-color:" + bgCol + ";" ); style.append("background-color:").append(bgCol).append(";");
break; break;
} }
@ -225,8 +205,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
} }
private void buildStyle_border( HSSFWorkbook workbook, StringBuilder style, private void buildStyle_border( HSSFWorkbook workbook, StringBuilder style,
String type, BorderStyle xlsBorder, short borderColor ) String type, BorderStyle xlsBorder, short borderColor ) {
{
if ( xlsBorder == BorderStyle.NONE ) { if ( xlsBorder == BorderStyle.NONE ) {
return; return;
} }
@ -244,12 +223,11 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
borderStyle.append( ExcelToHtmlUtils.getColor( color ) ); 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, void buildStyle_font( HSSFWorkbook workbook, StringBuilder style,
HSSFFont font ) HSSFFont font ) {
{
if ( font.getBold() ) if ( font.getBold() )
{ {
style.append( "font-weight:bold;" ); style.append( "font-weight:bold;" );
@ -258,11 +236,10 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
final HSSFColor fontColor = workbook.getCustomPalette().getColor( final HSSFColor fontColor = workbook.getCustomPalette().getColor(
font.getColor() ); font.getColor() );
if ( fontColor != null ) if ( fontColor != null )
style.append( "color: " + ExcelToHtmlUtils.getColor( fontColor ) style.append("color: ").append(ExcelToHtmlUtils.getColor(fontColor)).append("; ");
+ "; " );
if ( font.getFontHeightInPoints() != 0 ) if ( font.getFontHeightInPoints() != 0 )
style.append( "font-size:" + font.getFontHeightInPoints() + "pt;" ); style.append("font-size:").append(font.getFontHeightInPoints()).append("pt;");
if ( font.getItalic() ) if ( font.getItalic() )
{ {
@ -296,8 +273,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
} }
protected String getStyleClassName( HSSFWorkbook workbook, protected String getStyleClassName( HSSFWorkbook workbook,
HSSFCellStyle cellStyle ) HSSFCellStyle cellStyle ) {
{
final Short cellStyleKey = Short.valueOf( cellStyle.getIndex() ); final Short cellStyleKey = Short.valueOf( cellStyle.getIndex() );
String knownClass = excelStyleToClass.get( cellStyleKey ); String knownClass = excelStyleToClass.get( cellStyleKey );
@ -317,20 +293,17 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
} }
protected boolean processCell( HSSFCell cell, Element tableCellElement, protected boolean processCell( HSSFCell cell, Element tableCellElement,
int normalWidthPx, int maxSpannedWidthPx, float normalHeightPt ) int normalWidthPx, int maxSpannedWidthPx, float normalHeightPt ) {
{
final HSSFCellStyle cellStyle = cell.getCellStyle(); final HSSFCellStyle cellStyle = cell.getCellStyle();
String value; String value;
switch ( cell.getCellType() ) switch ( cell.getCellType() ) {
{
case STRING: case STRING:
// XXX: enrich // XXX: enrich
value = cell.getRichStringCellValue().getString(); value = cell.getRichStringCellValue().getString();
break; break;
case FORMULA: case FORMULA:
switch ( cell.getCachedFormulaResultType() ) switch ( cell.getCachedFormulaResultType() ) {
{
case STRING: case STRING:
HSSFRichTextString str = cell.getRichStringCellValue(); HSSFRichTextString str = cell.getRichStringCellValue();
if ( str != null && str.length() > 0 ) if ( str != null && str.length() > 0 )
@ -384,8 +357,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
final boolean noText = ExcelToHtmlUtils.isEmpty( value ); final boolean noText = ExcelToHtmlUtils.isEmpty( value );
final boolean wrapInDivs = !noText && isUseDivsToSpan() && !cellStyle.getWrapText(); final boolean wrapInDivs = !noText && isUseDivsToSpan() && !cellStyle.getWrapText();
if ( cellStyle.getIndex() != 0 ) if ( cellStyle.getIndex() != 0 ) {
{
@SuppressWarnings("resource") @SuppressWarnings("resource")
HSSFWorkbook workbook = cell.getRow().getSheet().getWorkbook(); HSSFWorkbook workbook = cell.getRow().getSheet().getWorkbook();
String mainCssClass = getStyleClassName( workbook, cellStyle ); 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(); StringBuilder builder = new StringBuilder();
for ( int c = 0; c < value.length(); c++ ) for ( int c = 0; c < value.length(); c++ )
{ {
@ -425,8 +396,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
Text text = htmlDocumentFacade.createText( value ); Text text = htmlDocumentFacade.createText( value );
if ( wrapInDivs ) if ( wrapInDivs ) {
{
Element outerDiv = htmlDocumentFacade.createBlock(); Element outerDiv = htmlDocumentFacade.createBlock();
outerDiv.setAttribute( "class", this.cssClassContainerDiv ); outerDiv.setAttribute( "class", this.cssClassContainerDiv );
@ -435,8 +405,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
innerDivStyle.append( "position:absolute;min-width:" ); innerDivStyle.append( "position:absolute;min-width:" );
innerDivStyle.append( normalWidthPx ); innerDivStyle.append( normalWidthPx );
innerDivStyle.append( "px;" ); innerDivStyle.append( "px;" );
if ( maxSpannedWidthPx != Integer.MAX_VALUE ) if ( maxSpannedWidthPx != Integer.MAX_VALUE ) {
{
innerDivStyle.append( "max-width:" ); innerDivStyle.append( "max-width:" );
innerDivStyle.append( maxSpannedWidthPx ); innerDivStyle.append( maxSpannedWidthPx );
innerDivStyle.append( "px;" ); innerDivStyle.append( "px;" );
@ -451,9 +420,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
innerDiv.appendChild( text ); innerDiv.appendChild( text );
outerDiv.appendChild( innerDiv ); outerDiv.appendChild( innerDiv );
tableCellElement.appendChild( outerDiv ); tableCellElement.appendChild( outerDiv );
} } else {
else
{
tableCellElement.appendChild( text ); tableCellElement.appendChild( text );
} }
@ -461,21 +428,18 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
} }
protected void processColumnHeaders( HSSFSheet sheet, int maxSheetColumns, protected void processColumnHeaders( HSSFSheet sheet, int maxSheetColumns,
Element table ) Element table ) {
{
Element tableHeader = htmlDocumentFacade.createTableHeader(); Element tableHeader = htmlDocumentFacade.createTableHeader();
table.appendChild( tableHeader ); table.appendChild( tableHeader );
Element tr = htmlDocumentFacade.createTableRow(); Element tr = htmlDocumentFacade.createTableRow();
if ( isOutputRowNumbers() ) if ( isOutputRowNumbers() ) {
{
// empty row at left-top corner // empty row at left-top corner
tr.appendChild( htmlDocumentFacade.createTableHeaderCell() ); tr.appendChild( htmlDocumentFacade.createTableHeaderCell() );
} }
for ( int c = 0; c < maxSheetColumns; c++ ) for ( int c = 0; c < maxSheetColumns; c++ ) {
{
if ( !isOutputHiddenColumns() && sheet.isColumnHidden( c ) ) if ( !isOutputHiddenColumns() && sheet.isColumnHidden( c ) )
continue; continue;
@ -492,8 +456,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
* first if <tt>{@link #isOutputRowNumbers()}==true</tt>) * first if <tt>{@link #isOutputRowNumbers()}==true</tt>)
*/ */
protected void processColumnWidths( HSSFSheet sheet, int maxSheetColumns, protected void processColumnWidths( HSSFSheet sheet, int maxSheetColumns,
Element table ) Element table ) {
{
// draw COLS after we know max column number // draw COLS after we know max column number
Element columnGroup = htmlDocumentFacade.createTableColumnGroup(); Element columnGroup = htmlDocumentFacade.createTableColumnGroup();
if ( isOutputRowNumbers() ) if ( isOutputRowNumbers() )
@ -513,9 +476,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
table.appendChild( columnGroup ); table.appendChild( columnGroup );
} }
protected void processDocumentInformation( protected void processDocumentInformation(SummaryInformation summaryInformation ) {
SummaryInformation summaryInformation )
{
if ( ExcelToHtmlUtils.isNotEmpty( summaryInformation.getTitle() ) ) if ( ExcelToHtmlUtils.isNotEmpty( summaryInformation.getTitle() ) )
htmlDocumentFacade.setTitle( 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 * @return maximum 1-base index of column that were rendered, zero if none
*/ */
protected int processRow( CellRangeAddress[][] mergedRanges, HSSFRow row, protected int processRow( CellRangeAddress[][] mergedRanges, HSSFRow row,
Element tableRowElement ) Element tableRowElement ) {
{
final HSSFSheet sheet = row.getSheet(); final HSSFSheet sheet = row.getSheet();
final short maxColIx = row.getLastCellNum(); final short maxColIx = row.getLastCellNum();
if ( maxColIx <= 0 ) if ( maxColIx <= 0 )
@ -615,18 +575,13 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
emptyCell = processCell( cell, tableCellElement, emptyCell = processCell( cell, tableCellElement,
getColumnWidth( sheet, colIx ), divWidthPx, getColumnWidth( sheet, colIx ), divWidthPx,
row.getHeight() / 20f ); row.getHeight() / 20f );
} } else {
else
{
emptyCell = true; emptyCell = true;
} }
if ( emptyCell ) if ( emptyCell ) {
{
emptyCells.add( tableCellElement ); emptyCells.add( tableCellElement );
} } else {
else
{
for ( Element emptyCellElement : emptyCells ) for ( Element emptyCellElement : emptyCells )
{ {
tableRowElement.appendChild( emptyCellElement ); tableRowElement.appendChild( emptyCellElement );
@ -642,15 +597,13 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
} }
protected void processRowNumber( HSSFRow row, protected void processRowNumber( HSSFRow row,
Element tableRowNumberCellElement ) Element tableRowNumberCellElement ) {
{
tableRowNumberCellElement.setAttribute( "class", "rownumber" ); tableRowNumberCellElement.setAttribute( "class", "rownumber" );
Text text = htmlDocumentFacade.createText( getRowName( row ) ); Text text = htmlDocumentFacade.createText( getRowName( row ) );
tableRowNumberCellElement.appendChild( text ); tableRowNumberCellElement.appendChild( text );
} }
protected void processSheet( HSSFSheet sheet ) protected void processSheet( HSSFSheet sheet ) {
{
processSheetHeader( htmlDocumentFacade.getBody(), sheet ); processSheetHeader( htmlDocumentFacade.getBody(), sheet );
final int physicalNumberOfRows = sheet.getPhysicalNumberOfRows(); final int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
@ -669,8 +622,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
final List<Element> emptyRowElements = new ArrayList<>( final List<Element> emptyRowElements = new ArrayList<>(
physicalNumberOfRows); physicalNumberOfRows);
int maxSheetColumns = 1; 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 ); HSSFRow row = sheet.getRow( r );
if ( row == null ) if ( row == null )
@ -687,16 +639,11 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
int maxRowColumnNumber = processRow( mergedRanges, row, int maxRowColumnNumber = processRow( mergedRanges, row,
tableRowElement ); tableRowElement );
if ( maxRowColumnNumber == 0 ) if ( maxRowColumnNumber == 0 ) {
{
emptyRowElements.add( tableRowElement ); emptyRowElements.add( tableRowElement );
} } else {
else if ( !emptyRowElements.isEmpty() ) {
{ for ( Element emptyRowElement : emptyRowElements ) {
if ( !emptyRowElements.isEmpty() )
{
for ( Element emptyRowElement : emptyRowElements )
{
tableBody.appendChild( emptyRowElement ); tableBody.appendChild( emptyRowElement );
} }
emptyRowElements.clear(); emptyRowElements.clear();
@ -709,8 +656,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
processColumnWidths( sheet, maxSheetColumns, table ); processColumnWidths( sheet, maxSheetColumns, table );
if ( isOutputColumnHeaders() ) if ( isOutputColumnHeaders() ) {
{
processColumnHeaders( sheet, maxSheetColumns, table ); processColumnHeaders( sheet, maxSheetColumns, table );
} }
@ -719,24 +665,20 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
htmlDocumentFacade.getBody().appendChild( table ); htmlDocumentFacade.getBody().appendChild( table );
} }
protected void processSheetHeader( Element htmlBody, HSSFSheet sheet ) protected void processSheetHeader( Element htmlBody, HSSFSheet sheet ) {
{
Element h2 = htmlDocumentFacade.createHeader2(); Element h2 = htmlDocumentFacade.createHeader2();
h2.appendChild( htmlDocumentFacade.createText( sheet.getSheetName() ) ); h2.appendChild( htmlDocumentFacade.createText( sheet.getSheetName() ) );
htmlBody.appendChild( h2 ); htmlBody.appendChild( h2 );
} }
public void processWorkbook( HSSFWorkbook workbook ) public void processWorkbook( HSSFWorkbook workbook ) {
{
final SummaryInformation summaryInformation = workbook final SummaryInformation summaryInformation = workbook
.getSummaryInformation(); .getSummaryInformation();
if ( summaryInformation != null ) if ( summaryInformation != null ) {
{
processDocumentInformation( summaryInformation ); processDocumentInformation( summaryInformation );
} }
if ( isUseDivsToSpan() ) if ( isUseDivsToSpan() ) {
{
// prepare CSS classes for later usage // prepare CSS classes for later usage
this.cssClassContainerCell = htmlDocumentFacade this.cssClassContainerCell = htmlDocumentFacade
.getOrCreateCssClass( cssClassPrefixCell, .getOrCreateCssClass( cssClassPrefixCell,
@ -745,8 +687,7 @@ public class ExcelToHtmlConverter extends AbstractExcelConverter
cssClassPrefixDiv, "position:relative;" ); cssClassPrefixDiv, "position:relative;" );
} }
for ( int s = 0; s < workbook.getNumberOfSheets(); s++ ) for ( int s = 0; s < workbook.getNumberOfSheets(); s++ ) {
{
HSSFSheet sheet = workbook.getSheetAt( s ); HSSFSheet sheet = workbook.getSheetAt( s );
processSheet( sheet ); processSheet( sheet );
} }

View File

@ -18,16 +18,14 @@ package org.apache.poi.hssf.converter;
import java.util.Arrays; import java.util.Arrays;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.HorizontalAlignment; 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.ss.util.CellRangeAddress;
import org.apache.poi.util.Beta; import org.apache.poi.util.Beta;
@Beta @Beta
public class ExcelToHtmlUtils extends AbstractExcelUtils public class ExcelToHtmlUtils extends AbstractExcelUtils {
{ public static void appendAlign( StringBuilder style, HorizontalAlignment alignment ) {
public static void appendAlign( StringBuilder style, HorizontalAlignment alignment )
{
String cssAlign = getAlign( alignment ); String cssAlign = getAlign( alignment );
if ( isEmpty( cssAlign ) ) if ( isEmpty( cssAlign ) )
return; return;
@ -44,14 +42,11 @@ public class ExcelToHtmlUtils extends AbstractExcelUtils
* *
* @see #getMergedRange(CellRangeAddress[][], int, int) * @see #getMergedRange(CellRangeAddress[][], int, int)
*/ */
public static CellRangeAddress[][] buildMergedRangesMap( HSSFSheet sheet ) public static CellRangeAddress[][] buildMergedRangesMap( Sheet sheet ) {
{
CellRangeAddress[][] mergedRanges = new CellRangeAddress[1][]; CellRangeAddress[][] mergedRanges = new CellRangeAddress[1][];
for ( final CellRangeAddress cellRangeAddress : sheet.getMergedRegions() ) for ( final CellRangeAddress cellRangeAddress : sheet.getMergedRegions() ) {
{
final int requiredHeight = cellRangeAddress.getLastRow() + 1; final int requiredHeight = cellRangeAddress.getLastRow() + 1;
if ( mergedRanges.length < requiredHeight ) if ( mergedRanges.length < requiredHeight ) {
{
CellRangeAddress[][] newArray = new CellRangeAddress[requiredHeight][]; CellRangeAddress[][] newArray = new CellRangeAddress[requiredHeight][];
System.arraycopy( mergedRanges, 0, newArray, 0, System.arraycopy( mergedRanges, 0, newArray, 0,
mergedRanges.length ); mergedRanges.length );
@ -59,18 +54,14 @@ public class ExcelToHtmlUtils extends AbstractExcelUtils
} }
for ( int r = cellRangeAddress.getFirstRow(); r <= cellRangeAddress for ( int r = cellRangeAddress.getFirstRow(); r <= cellRangeAddress
.getLastRow(); r++ ) .getLastRow(); r++ ) {
{
final int requiredWidth = cellRangeAddress.getLastColumn() + 1; final int requiredWidth = cellRangeAddress.getLastColumn() + 1;
CellRangeAddress[] rowMerged = mergedRanges[r]; CellRangeAddress[] rowMerged = mergedRanges[r];
if ( rowMerged == null ) if ( rowMerged == null ) {
{
rowMerged = new CellRangeAddress[requiredWidth]; rowMerged = new CellRangeAddress[requiredWidth];
mergedRanges[r] = rowMerged; mergedRanges[r] = rowMerged;
} } else {
else
{
final int rowMergedLength = rowMerged.length; final int rowMergedLength = rowMerged.length;
if ( rowMergedLength < requiredWidth ) if ( rowMergedLength < requiredWidth )
{ {
@ -89,5 +80,4 @@ public class ExcelToHtmlUtils extends AbstractExcelUtils
} }
return mergedRanges; return mergedRanges;
} }
} }

View File

@ -20,10 +20,8 @@ package org.apache.poi.ss.util;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assume.assumeTrue;
import java.util.Set; import java.util.Set;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import org.apache.commons.collections4.IteratorUtils; 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, B1, A2, B2));
assertCellRangesEqual(asArray(A1_B2), merge(A1, B2, A2, B1)); assertCellRangesEqual(asArray(A1_B2), merge(A1, B2, A2, B1));
// Partially mergeable: multiple possible mergings // Partially mergeable: multiple possible merges
// A B // A B
// 1 x x A1,A2,B1 --> A1:B1,A2 or A1:A2,B1 // 1 x x A1,A2,B1 --> A1:B1,A2 or A1:A2,B1
// 2 x // 2 x
@ -83,7 +81,7 @@ public final class TestCellRangeUtil {
return set; return set;
} }
private static <T> T[] asArray(T...ts) { private static CellRangeAddress[] asArray(CellRangeAddress...ts) {
return ts; return ts;
} }