org.apache.poi.openxml4j.exceptions.InvalidFormatException Java Examples

The following examples show how to use org.apache.poi.openxml4j.exceptions.InvalidFormatException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PoiTest.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Test
public void lastRowNum2333() throws IOException, InvalidFormatException {
    String file = TestFileUtil.getPath() + "fill" + File.separator + "simple.xlsx";
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new File(file));
    SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(xssfWorkbook);
    Sheet xssfSheet = xssfWorkbook.getSheetAt(0);
    Cell cell = xssfSheet.getRow(0).createCell(9);
    cell.setCellValue("testssdf是士大夫否t");

    FileOutputStream fileout = new FileOutputStream("d://test/r2" + System.currentTimeMillis() + ".xlsx");
    sxssfWorkbook.write(fileout);
    sxssfWorkbook.dispose();
    sxssfWorkbook.close();

    xssfWorkbook.close();
}
 
Example #2
Source File: ExcelTest.java    From azeroth with Apache License 2.0 6 votes vote down vote up
/**
 * @param args
 * @throws IOException
 * @throws InvalidFormatException
 */
public static void main(String[] args) throws InvalidFormatException, IOException {

    List<PersonSalaryInfo> list = new ExcelPerfModeReader("/Users/warlock/Desktop/人员导入模板.xlsx")
            .read(PersonSalaryInfo.class);

    System.out.println(list.get(0));

    //		String excelFilePath = "/Users/ayg/Desktop/test110.xlsx";
    //		ExcelWriter writer = new ExcelWriter(excelFilePath);
    //		writer.write(list, PersonSalaryInfo.class);
    //		writer.close();
    //		System.out.println(excelFilePath);

    //		ExcelMeta excelMeta = ExcelBeanHelper.getExcelMeta(PersonSalaryInfo.class);
    //		// 写标题
    //		for (int i = 1; i <= excelMeta.getTitleRowNum(); i++) {
    //			for (int j = 1; j <= excelMeta.getTitleColumnNum(); j++) {
    //				TitleMeta titleMeta = excelMeta.getTitleMeta(i, j);
    //				System.out.println(i + "-" + j + "-" + (titleMeta == null ? "" : titleMeta.getTitle()));
    //			}
    //		}
}
 
Example #3
Source File: RunProviderTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testNonEmptyDoc() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        XWPFRun run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("", run.getText(run.getTextPosition()));
        assertTrue(!iterator.hasNext());
    }
}
 
Example #4
Source File: RunProviderTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testNextWitLookAhead() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        // CHECKSTYLE:OFF
        assertTrue(iterator.hasElements(7));
        // CHECKSTYLE:ON
        XWPFRun run;
        run = iterator.lookAhead(1).getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.lookAhead(1).getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.lookAhead(2).getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        assertTrue(iterator.hasElements(4));
    }
}
 
Example #5
Source File: PoiExcelHelper.java    From bird-java with MIT License 6 votes vote down vote up
/**
 * 读取EXCEL文件
 *
 * @param stream      文件流
 * @param config      表头与Key映射
 * @param sheetIndex  sheet序号
 * @param headerIndex header行序号
 * @return excel数据
 */
public static List<Map<String, Object>> read(InputStream stream, Map<String, String> config, Integer sheetIndex, Integer headerIndex) {
    List<Map<String, Object>> result = new ArrayList<>();

    try (Workbook wb = WorkbookFactory.create(stream)) {
        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
        Sheet sheet = wb.getSheetAt(sheetIndex);
        if (sheet == null) return result;

        List<String> headKeys = getHeadKeys(sheet, config, headerIndex);
        if (CollectionUtils.isEmpty(headKeys)) return result;

        int max = sheet.getLastRowNum();
        for (int i = headerIndex + 1; i <= max; i++) {
            Map<String, Object> line = readLine(sheet.getRow(i), headKeys, evaluator);
            if (line == null) continue;
            result.add(line);
        }
    } catch (InvalidFormatException | IOException e) {
        logger.error("Excel流读取失败", e);
    }

    return result;
}
 
Example #6
Source File: ExcelParser.java    From excelastic with MIT License 6 votes vote down vote up
/**
 * Returns a workbook implementation based on the extension of the filname.
 *
 * @param file     stream representing a workbook
 * @param fileName the filename to determine a specific workbook implementation
 * @return a workbook implentation that supports the given file format
 * @throws ParserException when the file extension is unsupported
 * @throws IOException     when the given data is not a valid workbook
 */
private Workbook getWorkbook(File file, String fileName) throws ParserException, IOException {
    if (fileName.endsWith(OOXML)) {
        try {
            return new XSSFWorkbook(file);
        } catch (InvalidFormatException e) {
            throw new ParserException(e);
        }
    } else if (fileName.endsWith(XML97)) {
        return new HSSFWorkbook(new FileInputStream(file));
    } else {
        throw new ParserException(
                String.format("Unrecognized file extension for file %s, expected %s or %s.",
                        fileName, OOXML, XML97));
    }
}
 
Example #7
Source File: M2DocNewProjectWizard.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the sample template.
 * 
 * @param templateName
 *            the template name
 * @param variableName
 *            the variable name
 * @param variableValue
 *            the variable value
 * @param monitor
 *            the {@link IProgressMonitor}
 * @param project
 *            the {@link IllegalPropertySetDataException}
 * @return
 * @throws IOException
 *             if the template file can't be saved
 * @throws CoreException
 *             if the template file can't be saved
 * @throws InvalidFormatException
 *             if the sample template can't be read
 * @return the template {@link URI}
 */
private URI createSampleTemplate(final String templateName, final String variableName, final EObject variableValue,
        IProgressMonitor monitor, final IProject project)
        throws IOException, CoreException, InvalidFormatException {
    final URI res;

    final URIConverter uriConverter = new ExtensibleURIConverterImpl();
    final MemoryURIHandler handler = new MemoryURIHandler();
    uriConverter.getURIHandlers().add(0, handler);
    try (XWPFDocument sampleTemplate = M2DocUtils.createSampleTemplate(variableName, variableValue.eClass());) {
        final URI memoryURI = URI
                .createURI(MemoryURIHandler.PROTOCOL + "://resources/temp." + M2DocUtils.DOCX_EXTENSION_FILE);
        POIServices.getInstance().saveFile(uriConverter, sampleTemplate, memoryURI);

        try (InputStream source = uriConverter.createInputStream(memoryURI)) {
            final IFile templateFile = project.getFile(templateName);
            templateFile.create(source, true, monitor);
            res = URI.createPlatformResourceURI(templateFile.getFullPath().toString(), true);
        }
    }

    return res;
}
 
Example #8
Source File: RunIteratorTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testAccessEmptyIterator() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenIterator iterator = new TokenIterator(document);
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertFalse(iterator.hasNext());
        boolean hasException = false;
        try {
            iterator.next();
        } catch (NoSuchElementException e) {
            assertTrue(e instanceof NoSuchElementException);
            hasException = true;
        }
        assertTrue(hasException);
    }
}
 
Example #9
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getMissingVariablesInHeader() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/missingVariablesInHeader.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> missingVariables = properties.getMissingVariables();

        assertEquals(16, missingVariables.size());
        assertEquals("linkNamelinkText", missingVariables.get(0));
        assertEquals("bookmarkName", missingVariables.get(1));
        assertEquals("queryInBookmark", missingVariables.get(2));
        assertEquals("ifCondition", missingVariables.get(3));
        assertEquals("queryInIf", missingVariables.get(4));
        assertEquals("elseIfCondition", missingVariables.get(5));
        assertEquals("queryInElseIf", missingVariables.get(6));
        assertEquals("queryInElse", missingVariables.get(7));
        assertEquals("letExpression", missingVariables.get(8));
        assertEquals("queryInLet", missingVariables.get(9));
        assertEquals("forExpression", missingVariables.get(10));
        assertEquals("queryInFor", missingVariables.get(11));
        assertEquals("queryExpression", missingVariables.get(12));
        assertEquals("aqlInSelect", missingVariables.get(13));
        assertEquals("aqlLetExpression", missingVariables.get(14));
        assertEquals("aqlLetBody", missingVariables.get(15));
    }
}
 
Example #10
Source File: OOXMLBleach.java    From DocBleach with MIT License 6 votes vote down vote up
void remapContentType(BleachSession session, PackagePart part) throws InvalidFormatException {
  String oldContentType = part.getContentType();
  if (!REMAPPED_CONTENT_TYPES.containsKey(oldContentType)) {
    return;
  }

  String newContentType = REMAPPED_CONTENT_TYPES.get(part.getContentType());
  part.setContentType(newContentType);

  LOGGER.debug(
      "Content type of '{}' changed from '{}' to '{}'",
      part.getPartName(),
      oldContentType,
      newContentType);

  Threat threat = Threat.builder()
      .type(ThreatType.UNRECOGNIZED_CONTENT)
      .severity(ThreatSeverity.LOW)
      .action(ThreatAction.DISARM)
      .location(part.getPartName().getName())
      .details("Remapped content type: " + oldContentType)
      .build();

  session.recordThreat(threat);
}
 
Example #11
Source File: ImportExcel.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 构造函数
 * @param fileName 导入文件对象
 * @param headerNum 标题行号,数据行号=标题行号+1
 * @param sheetIndex 工作表编号
 * @throws InvalidFormatException 
 * @throws IOException 
 */
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) 
		throws InvalidFormatException, IOException {
	if (StringUtils.isBlank(fileName)){
		throw new RuntimeException("导入文档为空!");
	}else if(fileName.toLowerCase().endsWith("xls")){    
		this.wb = new HSSFWorkbook(is);    
       }else if(fileName.toLowerCase().endsWith("xlsx")){  
       	this.wb = new XSSFWorkbook(is);
       }else{  
       	throw new RuntimeException("文档格式不正确!");
       }  
	if (this.wb.getNumberOfSheets()<sheetIndex){
		throw new RuntimeException("文档中没有工作表!");
	}
	this.sheet = this.wb.getSheetAt(sheetIndex);
	this.headerNum = headerNum;
	log.debug("Initialize success.");
}
 
Example #12
Source File: DelimitedRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Converts the specified number of rows of a Excel file into JSON and returns
 * them as a String.
 *
 * @param input the Excel file to convert into JSON
 * @param numRows the number of rows from the Excel file to convert
 * @return a string with the JSON of the Excel rows
 * @throws IOException excel file could not be read
 * @throws InvalidFormatException file is not in a valid excel format
 */
private String convertExcelRows(File input, int numRows) throws IOException, InvalidFormatException {
    try (Workbook wb = WorkbookFactory.create(input)) {
        // Only support single sheet files for now
        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
        Sheet sheet = wb.getSheetAt(0);
        DataFormatter df = new DataFormatter();
        JSONArray rowList = new JSONArray();
        String[] columns;
        for (Row row : sheet) {
            if (row.getRowNum() <= numRows) {
                //getLastCellNumber instead of getPhysicalNumberOfCells so that blank values don't shift cells
                columns = new String[row.getLastCellNum()];
                for (int i = 0; i < row.getLastCellNum(); i++ ) {
                    columns[i] = df.formatCellValue(row.getCell(i), evaluator);
                }
                rowList.add(columns);
            }
        }
        return rowList.toString();
    }
}
 
Example #13
Source File: RawCopier.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get Xml With Ouput relation Id.
 * 
 * @param inputRelationIdToOutputMap
 *            the relation ID mapping
 * @param inputPartURIToOutputPartURI
 *            the mapping form input part {@link PackagePartName} to output par {@link PackagePartName}
 * @param outputBody
 *            the input {@link IBody}
 * @param inputBody
 *            the ouput {@link IBody}
 * @param xmlObject
 *            the {@link XmlObject} to walk
 * @throws XmlException
 *             XmlException
 * @throws InvalidFormatException
 *             if image copy fails
 * @throws IOException
 *             if a {@link PackagePart} can't be read
 * @throws NoSuchAlgorithmException
 *             if MD5 can't be read
 */
private void updateRelationIds(Map<String, String> inputRelationIdToOutputMap,
        Map<URI, URI> inputPartURIToOutputPartURI, IBody inputBody, IBody outputBody, XmlObject xmlObject)
        throws XmlException, InvalidFormatException, NoSuchAlgorithmException, IOException {
    final XmlObject idAttr = xmlObject.selectAttribute(RELATIONSHIPS_URI, "id");
    if (idAttr != null) {
        updateRelationAttribute(inputRelationIdToOutputMap, inputPartURIToOutputPartURI, inputBody, outputBody,
                idAttr);
    } else {
        final XmlObject embedAttr = xmlObject.selectAttribute(RELATIONSHIPS_URI, "embed");
        if (embedAttr != null) {
            updateRelationAttribute(inputRelationIdToOutputMap, inputPartURIToOutputPartURI, inputBody, outputBody,
                    embedAttr);
        }
    }
    final XmlCursor cursor = xmlObject.newCursor();
    if (cursor.toFirstChild()) {
        updateRelationIds(inputRelationIdToOutputMap, inputPartURIToOutputPartURI, inputBody, outputBody,
                cursor.getObject());
        while (cursor.toNextSibling()) {
            updateRelationIds(inputRelationIdToOutputMap, inputPartURIToOutputPartURI, inputBody, outputBody,
                    cursor.getObject());
        }
    }
    cursor.dispose();
}
 
Example #14
Source File: FlatFileLoader.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * generates an excel parser for the file
 * 
 * @param file        binary file
 * @param preferedtab name of the prefered tab to use
 * @return the Excel Reader
 */
public ExcelReader generateExcelParser(SFile file, String preferedtab) {
	ByteArrayInputStream batch = new ByteArrayInputStream(file.getContent());
	try {
		ExcelReader parser = new ExcelReader(batch);
		if (preferedtab != null)
			parser.GoToSheet(preferedtab);
		return parser;
	} catch (InvalidFormatException | IOException e) {
		logger.warning("------------------ Exception in setting up Excel file ---- " + e.getMessage());
		for (int i = 0; i < e.getStackTrace().length; i++) {
			logger.warning("       " + e.getStackTrace()[i]);
		}
		throw new RuntimeException("Error in opening excel file " + file.getFileName() + " Original error "
				+ e.getClass() + " - " + e.getMessage());
	}
}
 
Example #15
Source File: OOXMLBleach.java    From DocBleach with MIT License 5 votes vote down vote up
public void sanitize(OPCPackage pkg, BleachSession session)
    throws BleachException, InvalidFormatException {
  LOGGER.trace("File opened");
  Iterator<PackagePart> it = getPartsIterator(pkg);

  pkg.ensureRelationships();

  sanitize(session, pkg, pkg.getRelationships());

  PackagePart part;
  while (it.hasNext()) {
    part = it.next();
    sanitize(session, pkg, part);

    OOXMLTagHelper.removeExternalDataTagAndDDE(session, part);

    if (!part.isRelationshipPart()) {
      sanitize(session, part, part.getRelationships());
    }

    if (part.isDeleted()) {
      continue;
    }

    remapContentType(session, part);
  }

  // If threats have been removed, then add the dummy file so the relationship
  // still refers to an existing dummy object.
  if (session.threatCount() > 0) {
    pushDummyFile(pkg);
  }
}
 
Example #16
Source File: ExcelTest.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 * @throws IOException
 * @throws InvalidFormatException
 */
public static void main(String[] args) throws InvalidFormatException, IOException {
	//普通方式读取
	String excelFilePath = "/Users/jiangwei/Desktop/invorderdet_template.xlsx";

	//大文件读取防止内存溢出
	List<SimpleSalaryInfo> list = new ExcelPerfModeReader(excelFilePath).read(SimpleSalaryInfo.class);

	System.out.println(JsonUtils.toPrettyJson(list));

}
 
Example #17
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void getUnusedVariablesInFooter() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/unusedVariablesInFooter.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> unusedVariables = properties.getUnusedDeclarations();

        assertEquals(1, unusedVariables.size());
        assertEquals("unusedVariable", unusedVariables.get(0));
    }
}
 
Example #18
Source File: OOXMLBleach.java    From DocBleach with MIT License 5 votes vote down vote up
private static PackagePartName createPartName(final String name) {
  PackagePartName res = null;

  try {
    res = PackagingURIHelper.createPartName(name);
  } catch (InvalidFormatException ex) {
    LOGGER.error("Cannot initialize the PackagePartName: ", ex);
  }

  return res;
}
 
Example #19
Source File: ExcelTemplateWriter.java    From azeroth with Apache License 2.0 5 votes vote down vote up
/**
 * 构造方法,传入需要操作的excel文件路径
 *
 * @param outputPath 需要操作的excel文件的路径
 * @throws IOException            IO流异常
 * @throws InvalidFormatException 非法的格式异常
 */
public ExcelTemplateWriter(String templatePath, String outputPath) throws IOException, InvalidFormatException {
    this.templatePath = templatePath;
    File file = new File(outputPath);
    boolean exists = file.exists();
    if (!exists) { file.createNewFile(); }
    outputStream = new FileOutputStream(file);
    this.workbook = createWorkbook();
}
 
Example #20
Source File: AttachmentExportUtil.java    From myexcel with Apache License 2.0 5 votes vote down vote up
/**
 * 加密导出
 *
 * @param workbook workbook
 * @param fileName fileName
 * @param response response
 * @param password password
 */
public static void encryptExport(final Workbook workbook, String fileName, HttpServletResponse response, final String password) {
    if (workbook instanceof HSSFWorkbook) {
        throw new IllegalArgumentException("Document encryption for.xls is not supported");
    }
    Path path = null;
    try {
        String suffix = Constants.XLSX;
        path = TempFileOperator.createTempFile("encrypt_temp", suffix);
        workbook.write(Files.newOutputStream(path));

        final POIFSFileSystem fs = new POIFSFileSystem();
        final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
        final Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);

        try (OPCPackage opc = OPCPackage.open(path.toFile(), PackageAccess.READ_WRITE);
             OutputStream os = enc.getDataStream(fs)) {
            opc.save(os);
        }
        if (!fileName.endsWith(suffix)) {
            fileName += suffix;
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        setAttachmentConfig(fileName, response);
        fs.writeFilesystem(response.getOutputStream());
    } catch (IOException | InvalidFormatException | GeneralSecurityException e) {
        throw new RuntimeException(e);
    } finally {
        clear(workbook);
        TempFileOperator.deleteTempFile(path);
    }
}
 
Example #21
Source File: OOXMLBleachTest.java    From DocBleach with MIT License 5 votes vote down vote up
@Test
@Disabled
void remapsMacroEnabledDocumentType() throws InvalidFormatException {
  // Not implemented for now. :(
  ContentType ct;

  for (String contentType : DYNAMIC_TYPES) {
    ct = new ContentType(contentType);

    assertTrue(instance.isForbiddenType(ct), contentType + " should be a forbidden type");
  }
}
 
Example #22
Source File: OOXMLBleach.java    From DocBleach with MIT License 5 votes vote down vote up
/**
 * The dummy file tries to prevent Microsoft Office from crashing because they forgot a lot of "!=
 * null" while checking if a resource is valid.
 *
 * @param pkg Document to put the file in
 */
private void pushDummyFile(OPCPackage pkg) throws InvalidFormatException {

  try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    bos.write(DUMMY_FILE_CONTENT.getBytes());
    pkg.createPart(
        PackagingURIHelper.createPartName(DUMMY_FILE_PART_NAME), ContentTypes.TEXT_PLAIN, bos);
  } catch (IOException ex) {
    LOGGER.error(
        "Error occured while pushing the file in the document. But, it's not that critical so I'm gonna continue.",
        ex);
  }
}
 
Example #23
Source File: POIServices.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get OPCPackage from template file.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param templateURI
 *            the template {@link URI}
 * @return OPCPackage
 * @throws IOException
 *             IOException
 */
private OPCPackage getOPCPackage(URIConverter uriConverter, URI templateURI) throws IOException {
    OPCPackage oPackage;
    try (InputStream is = uriConverter.createInputStream(templateURI)) {
        try {
            oPackage = OPCPackage.open(is);

        } catch (InvalidFormatException e) {
            throw new IllegalArgumentException("Couldn't open template file", e);
        }
    }
    return oPackage;
}
 
Example #24
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void parseVariable() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/properties-template.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final Map<String, String> variables = properties.getVariables();
        assertEquals(3, variables.size());
        assertEquals("ecore::EPackage", variables.get("variable1"));
        assertEquals("ecore::EClass", variables.get("variable2"));
        assertEquals(null, variables.get("variable3"));
    }
}
 
Example #25
Source File: TemplateValidationGeneratorTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Ensure that the validation generation produces a document with an warning.
 * 
 * @throws InvalidFormatException
 * @throws IOException
 * @throws DocumentParserException
 * @throws DocumentGenerationException
 */
@Test
public void testWarningGeneration()
        throws InvalidFormatException, IOException, DocumentParserException, DocumentGenerationException {
    IQueryEnvironment queryEnvironment = org.eclipse.acceleo.query.runtime.Query
            .newEnvironmentWithDefaultServices(null);
    final File tempFile = File.createTempFile("testParsingErrorSimpleTag", ".docx");

    try (DocumentTemplate documentTemplate = M2DocUtils.parse(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/notEmpty/notEmpty-template.docx"), queryEnvironment,
            new ClassProvider(this.getClass().getClassLoader()), new BasicMonitor())) {
        final XWPFRun location = ((XWPFParagraph) documentTemplate.getDocument().getBodyElements().get(0)).getRuns()
                .get(0);
        documentTemplate.getBody().getValidationMessages().add(new TemplateValidationMessage(
                ValidationMessageLevel.WARNING, "XXXXXXXXXXXXXXXXXXXXXXXX", location));
        M2DocUtils.serializeValidatedDocumentTemplate(URIConverter.INSTANCE, documentTemplate,
                URI.createFileURI(tempFile.getAbsolutePath()));
    }
    assertTrue(new File(tempFile.getAbsolutePath()).exists());

    try (FileInputStream resIs = new FileInputStream(tempFile.getAbsolutePath());
            OPCPackage resOPackage = OPCPackage.open(resIs);
            XWPFDocument resDocument = new XWPFDocument(resOPackage);) {

        final XWPFRun messageRun = M2DocTestUtils.getRunContaining(resDocument, "XXXXXXXXXXXXXXXXXXXXXXXX");

        assertNotNull(messageRun);
        assertEquals("XXXXXXXXXXXXXXXXXXXXXXXX", messageRun.text());
        assertEquals("FFA500", messageRun.getColor());
    }

    tempFile.delete();
}
 
Example #26
Source File: PoiTest.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Test
public void lastRowNum233443() throws IOException, InvalidFormatException {
    String file = "d://test/em0.xlsx";
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new File(file));
    XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
    System.out.println(xssfSheet.getLastRowNum());
    System.out.println(xssfSheet.getRow(0));

}
 
Example #27
Source File: PoiTest.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Test
public void cp() throws IOException, InvalidFormatException {
    String file = "d://test/tt.xlsx";
    SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file));
    SXSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
    LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
    SXSSFRow row = xssfSheet.getRow(0);
    LOGGER.info("第一行数据:{}", row);
    xssfSheet.createRow(20);
    LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
}
 
Example #28
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
/** 
 * Signs the Excel OOXML file and writes it to the final outputstream
 * 
 * @param privateKey private Key for signing
 * @param x509List List of certificates for signing. First item must be the private key for signing.
 * @param password optional password for encryption, if used
 * @param hashAlgorithm hash algorithm to be used
 * 
 * @throws MarshalException 
 * @throws XMLSignatureException 
 * @throws IOException 
 * @throws FormatNotUnderstoodException 
 */
public void sign(Key privateKey, List<X509Certificate> x509List, String password, HashAlgorithm hashAlgorithm) throws XMLSignatureException, MarshalException, IOException, FormatNotUnderstoodException {
	if (this.tempSignFileOS!=null) { // close it we sign only a closed temporary file
		this.tempSignFileOS.close();
	}
	SignatureConfig sc = new SignatureConfig();
       sc.addSignatureFacet(new OOXMLSignatureFacet());
       sc.addSignatureFacet(new KeyInfoSignatureFacet());
       sc.addSignatureFacet(new XAdESSignatureFacet());
       sc.addSignatureFacet(new Office2010SignatureFacet());
	sc.setKey((PrivateKey)privateKey);
	sc.setSigningCertificateChain(x509List);
	sc.setDigestAlgo(hashAlgorithm);
	FileInputStream tempSignFileIS = null;
	try {
		
		InputStream tmpFileInputStream = new FileInputStream(this.tempSignFile);
		if (password==null) {
			this.signUnencryptedOpcPackage(tmpFileInputStream, sc);
		} else {
			this.signEncryptedPackage(tmpFileInputStream, sc, password);
		}
		
	} catch (InvalidFormatException | IOException e) {
		LOG.error(e);
	} finally {
		if (this.finalOutputStream!=null) {
			this.finalOutputStream.close();
		}
		if (tempSignFileIS!=null) {
			tempSignFileIS.close();
		}
	}
}
 
Example #29
Source File: OOXMLBleachTest.java    From DocBleach with MIT License 5 votes vote down vote up
@Test
@Disabled
void isForbiddenType() throws InvalidFormatException {
  ContentType ct;

  // Block PostScript
  ct = new ContentType("application/postscript");
  assertTrue(instance.isForbiddenType(ct));
}
 
Example #30
Source File: DataFormatTest.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
@Test
public void tests1() throws IOException, InvalidFormatException {
    String file = "D://test/dataformat1.xlsx";
    List<DateFormatData> list = EasyExcel.read(file, DateFormatData.class, null).sheet().doReadSync();
    for (DateFormatData data : list) {
        LOGGER.info("返回:{}", JSON.toJSONString(data));
    }
}